Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragment handle back button press [duplicate]

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]

like image 841
skayred Avatar asked Nov 03 '11 08:11

skayred


3 Answers

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;
    }
} );
like image 64
Mark Allison Avatar answered Nov 06 '22 10:11

Mark Allison


I'd rather do something like this:

private final static String TAG_FRAGMENT = "TAG_FRAGMENT";

private void showFragment() {
    final Myfragment fragment = new MyFragment();
    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
    transaction.addToBackStack(null);
    transaction.commit();
}

@Override
public void onBackPressed() {
    final Myfragment fragment = (Myfragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);

    if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
        super.onBackPressed();
    }
}
like image 274
Pedro Andrade Avatar answered Nov 06 '22 09:11

Pedro Andrade


if you overide the onKey method for the fragment view you're gonna need :

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i(tag, "keyCode: " + keyCode);
                if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                    Log.i(tag, "onKey Back listener is working!!!");
                    getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    return true;
                } 
                return false;
            }
        });
like image 131
ANemati Avatar answered Nov 06 '22 10:11

ANemati