I add Fragments to my Activity dynamically based on user interaction. When I press the back key, the fragments are popped. However when I press the back key for the fragment which was first added to the stack, the ‘Activity’ shows an empty layout. I would like the Activity to call `finish()’ at this point and disappear. I’ve tried:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if(keyCode == KeyEvent.KEYCODE_BACK){
if(getFragmentManager().getBackStackEntryCount()==0){
finish();
return true;
}
}
return true;
}
But this has the effect of blocking the back key functionality. Any pointers in the right direction are appreciated.
Change the second
return true;toreturn false;to indicate that you did NOT handle the keypress. This should close the activity when the back stack is empty, and leave it as is otherwise.