skayred skayred - 4 months ago 126x
Android Question

Android Fragment handle back button press

I have some fragments in my activity

[1], [2], [3], [4], [5], [6]

And on Back Button Press I must to return from [2] to [1] if current active fragment is [2], or do nothing otherwise.

What is the best practise to do that?

EDIT: Application must not return to [2] from [3]...[6]


When you are transitioning between Fragments, call addToBackStack() as part of your FragmentTransaction:

FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace(, new MyFragment() ).addToBackStack( "tag" ).commit();

If you require more detailed control (i.e. when some Fragments are visible, you want to suppress the back key) you can set an OnKeyListener on the parent view of your fragment:

//You need to add the following line for this solution to work; thanks skayred
fragment.getView().setOnKeyListener( new OnKeyListener()
    public boolean onKey( View v, int keyCode, KeyEvent event )
        if( keyCode == KeyEvent.KEYCODE_BACK )
            return true;
        return false;
} );