Skip to content Skip to sidebar Skip to footer

How To Handle Back Button To Go To Specific Fragment?

I making project with navigation drawer with fragment, the navigation have 3 fragment. I have problem, when i am at third fragment and i pressed back button the app suddenly close,

Solution 1:

Use this code in your Activity

@Override
    public void onBackPressed() {
        Fragment  f = getSupportFragmentManager().findFragmentById(R.id.maincontainer);
        if (f instanceof FirstFragment) {
           // do operations

        } else if (f instanceof SecondFragment) {
           // do operations

        }  else if (f instanceof ThirdFragment) {
           // do operations

        }else {
            super.onBackPressed();
        }

    }

and use ....

getSupportFragmentManager().popBackStack();

for removing fragments from your STACK


Solution 2:

You should add your fragments to backstack when adding them so Android will handle the backstack popping for your.

You can read more here: https://developer.android.com/training/implementing-navigation/temporal.html

So, your code will be the following:

fragmentTransaction.remove(fragment);
fragmentTransaction.replace(R.id.frame_container, fragment);
fragmentTransaction.addToBackStack();
fragmentTransaction.commit();

Solution 3:

When you call fragmentTransaction.replace() for the fragment that you want to return to after you press the Back button, try to add this to backStack, like this:

private void callFragment(Fragment fragment) {
        fragmentTransaction = fragmentManager.beginTransaction();
        if (fragment instanceof Monitoring)
            fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.frame_container, fragment);
        fragmentTransaction.commit();
    }

Solution 4:

  @Override
public void onBackPressed() {
    // This overrides default behavior for onBackPressed so that it does nothing.
    // This fixes the bug where when you disconnect the watch from wire, and reconnect,
    // the current current fragment will pop out.
    Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
    if (f instanceof CustomFragmentClass) {// do something with f
        ((CustomFragmentClass) f).doSomething();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_holder,new FragmentSample());
transaction.commit();
    }
}

Post a Comment for "How To Handle Back Button To Go To Specific Fragment?"