Reputation: 1127
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.
Upvotes: 9
Views: 2775
Reputation: 15766
Where are you adding your very first fragment? Don't add that transaction to the back stack it should work the way you want it.
Upvotes: 7
Reputation: 14274
Change the second return true;
to return 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.
Upvotes: 5