Question

I have a TabActivity and want to catch and handle presses of HOME and BACK. Where do I need to catch these events?

In my subclass of TabActivity I implement the following:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        // Code handling
    }

    return super.onKeyDown(keyCode, event);
}

Didn't work.

So I placed a breakpoint on the switch statement line. But this function never gets called, whether I press volume up/down, menu, home, or back. Where do I need to catch these KeyEvents?

Was it helpful?

Solution 3

Each tab's Activity handled the "back" presses.

OTHER TIPS

It turns out to be pretty easy. Add the following code to your child tab activity :

 @Override
  public void onBackPressed() {
    this.getParent().onBackPressed();   
  }

Then in the TabActivity do the real logic:

 @Override
  public void onBackPressed() {
    // Called by children
  }

Otherwise, the children will intercept and consume the event without notifying the tab host.

I had the same issue and found overriding dispatchKeyEvent worked.

An example of which can be found here for back button press:

http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

I have a TabActivity and want to catch and handle presses of HOME and BACK. Where do I need to catch these events?

You cannot "handle presses of HOME", ever.

With respect to BACK, you can use onKeyDown() (for Android 1.x) or onBackPressed() (for Android 2.x). However, your TabActivity may be too late. For example, if you have activities as the contents of your tabs, it may be that one of them is catching the BACK press and arranging for normal processing (i.e., closing up of the activity). Since I avoid activities-as-tabs like the plague (except for one book example), I have not experimented with BACK button processing in that scenario.

try this in your oncreate()

setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_GLOBAL);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top