开发者

onKeyDown or onBackPressed in a parent activity

开发者 https://www.devze.com 2023-03-06 01:18 出处:网络
I have a TabActivity that shows other Activities as the content based on which tab is selected. What I want to do is from the \'parent\' Activity try to capture the back key press, but neither onKeyDo

I have a TabActivity that shows other Activities as the content based on which tab is selected. What I want to do is from the 'parent' Activity try to capture the back key press, but neither onKeyDown() nor onBackPressed() ever get c开发者_JAVA百科alled in the parent... it's being handled by the 'child' Activities. Is there any way to have it pass up to the 'parent' Activity?


Why not just using, from within the child Activity:

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


You could set up a communication procedure between the TabActivity and his childs.

I created a static Handler in the TabActivity which was initialized in the onCreate of the TabActivity.

Then i created a static getHandler() method (in the TabActivity ).

Now a snippet to achieve your question for your childs would be:

@Override
public void onBackPressed () {
    MyTabActivity.getHandler().sendEmptyMessage(MyTabActivity.BACK_PRESSED);
}


I have encountered the same problem as well. I sovled it this way:

@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
    {
        //things u want to do when back key pressed
    }    
    return super.dispatchKeyEvent(event);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号