Search code examples
androiddialogandroid-tabhostbackconfirm

Android TabHost - catch back button


I have an Android app that uses TabHost, the activity that calls the others based on the selected tab is simply called Main.java. I have tried to override the on back button event inside of the Main.java class, however it does not seem to see it. I am trying to display a dialog window and confirm with the user that they want to sign out, and if they click OK have it completely close the app (not just send to background) and if they click Cancel, obviously have it stay open. Any suggestions as to why this doesn't seem to work?

@Override
public void onBackPressed() 
{               
     AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
     alert.setMessage("Test dialog");
     alert.show();
}

Solution

  • 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
     AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
     alert.setMessage("Test dialog");
     alert.show();
    }
    

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