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
@OverridepublicvoidonBackPressed() {
Fragmentf= getSupportFragmentManager().findFragmentById(R.id.maincontainer);
if (f instanceof FirstFragment) {
// do operations
} elseif (f instanceof SecondFragment) {
// do operations
} elseif (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:
privatevoidcallFragment(Fragment fragment) {
fragmentTransaction = fragmentManager.beginTransaction();
if (fragment instanceofMonitoring)
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.frame_container, fragment);
fragmentTransaction.commit();
}
Solution 4:
@OverridepublicvoidonBackPressed() {
// 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.Fragmentf= getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof CustomFragmentClass) {// do something with f
((CustomFragmentClass) f).doSomething();
FragmentTransactiontransaction= getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_holder,newFragmentSample());
transaction.commit();
}
}
Post a Comment for "How To Handle Back Button To Go To Specific Fragment?"