开发者

Help prevent Back button from closing sub-activity

开发者 https://www.devze.com 2023-01-26 05:30 出处:网络
I have a main activity.It\'s main purpose is to handle Tab menu.If a user click a tab it\'ll load another activity as a sub-activity, still showing the tab menu. I am using Intent to do this:

I have a main activity. It's main purpose is to handle Tab menu. If a user click a tab it'll load another activity as a sub-activity, still showing the tab menu. I am using Intent to do this:

setContent(new Intent(this,B.class))

This sub-activity has an onclick function as well. If the user clicks one of the links it'll load xml layout file using setContentView command:

setContentView(R.l开发者_StackOverflow中文版ayout.B1);

Now, when the back button is pressed while xml file is loaded, it'll close the entire application. Is there a way to prevent this, say, return to the sub-activity or the main activity?

thanks for all your help.


You should override the onBackPressed method in your activity or sub activity:

@Override
public void onBackPressed() {       
    //TODO Do your task here
}


In your sub activity you should override the fallowing:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {

       if (keyCode == KeyEvent.KEYCODE_BACK)  //Override Keyback to do nothing in this case.
       {
           return true;
       }
       return super.onKeyDown(keyCode, event);  //-->All others key will work as usual
   }
0

精彩评论

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

关注公众号