Android Fragment handle back button press

skayred picture skayred · Nov 3, 2011 · Viewed 560.4k times · Source

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]

Answer

Mark Allison picture Mark Allison · Nov 3, 2011

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

FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, 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().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            return true;
        }
        return false;
    }
} );