Search code examples
androidback-button

Help prevent Back button from closing sub-activity


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.layout.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.


Solution

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

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