问题
I have an app that contain a navigation drawer one of the fragments is the home fragment I want the app when the back button pressed in some other fragments to go to the home fragment for example if the user pressed on fr1 then fr2 then fr3 I want it to return back to the home button (where fr1,2,3 are the fragments of the navigation drawer and notice that there is other fragments in the app I don't want them to go to the home when back button pressed)
回答1:
If you have multiple fragments in your backstack you won't get to your home fragment just by popBackStack() as it just reverses one last operation. For example, it you have 3 fragments (home, fr1, fr2) first you'll get to fr2 and just then to home. If you want to get to home fragment directly onBackPress() you should replace what you currently have with your home fragment.
@Override
public void onBackPressed() {
int stackCount = getFragmentManager().getBackStackEntryCount();
if (stackCount == 1) {
super.onBackPressed(); // if you don't have any fragments in your backstack yet.
} else {
// just replace container with fragment as you normally do;
FragmentManager fm = getFragmentManager();
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//clear backstackfirst and then you can exit the app onbackpressed from home fr
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.container, new HomeFragment());
transaction.commit();
}
}
EDIT: How to check the current visible fragment
Fragment f = getFragmentManager().findFragmentById(R.id.container);
if (f instanceof HomeFragment) {
//do smth
}
回答2:
You can override the onBackPressed() method inside your Activity, and put your Fragment transaction code inside it. I don't know exactly your operation, so below I've written a generic example you can use:
@Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
来源:https://stackoverflow.com/questions/48505050/how-to-make-fragment-replaced-by-a-specific-fragment-when-back-button-pressed