Question

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();
}
Was it helpful?

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.

OTHER TIPS

I know this is coming very late but it may still help someone

Please add the below code to the TabActivity that is hosting other activities and also add the code to every child Activity that is been hosted with the Tabhost. it worked for me.

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (android.os.Build.VERSION.SDK_INT > 5
                && keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            Log.d("CDA", "onKeyDown Called");
            onBackPressed();
            return true; 
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
       Log.d("CDA", "onBackPressed Called");
       Intent setIntent = new Intent(Intent.ACTION_MAIN);
       setIntent.addCategory(Intent.CATEGORY_HOME);
       setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       startActivity(setIntent);
    }

Best of luck.

Hi All below is my solution for this question -

//////---------------------------/////////////

FragmentManager mFragmentManager = getSupportFragmentManager();

@Override
public void onBackPressed() {

    if (getParent() instanceof TabHostActivity) {
        int count = mFragmentManager.getBackStackEntryCount();
        if(count == 0){
            // TODO: Call your exist alert
        }
        else{
             super.onBackPressed();  
        }
    }
    else{
         super.onBackPressed();  
    }
}


//////---------------------------/////////////
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top