Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle back key when the last fragment is popped

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.

like image 267
Pierre Rymiortz Avatar asked Oct 24 '12 03:10

Pierre Rymiortz


1 Answers

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.

like image 108
James McCracken Avatar answered Oct 13 '22 20:10

James McCracken