How to stop back press button from going back to each fragment that was opened in the activity?
I am using this to launch a new fragment depending on the screen size of the device.
FragmentManager fragMgr = getSupportFragmentManager();
releaseInfo开发者_运维知识库Fragment release = (releaseInfoFragment)fragMgr.findFragmentById(R.id.release);
release = releaseInfoFragment.newInstance(url);
FragmentTransaction xaction = fragMgr.beginTransaction();
xaction.replace(R.id.release, release)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
}
The problem is when the user presses the back press button, the it goes back to each fragment that was opened during the activities life cycle. How can i make it where it doesnt do this? I just want it to remove the fragment once its pressed the first time, and then go back to the following activity on the second click.
How do i go about doing this?
If you don't want to go back through every Fragment, remove addToBackStack(null)
from your transaction. The function call addToBackStack(null)
is an instruction to add the Fragment to the back stack.
EDIT
I don't know of any simple way to remove all the Fragments from the back stack. Of the top of my head, I suggest this:
- Leave the call to
addToBackStack(null)
in so that all Fragments are added to the back stack - Override your Activity's
onBackPressed()
method and usepopBackStack()
to pop all the Fragments
Looking at the Android documentation for popBackStack()
, it looks like there are a couple of nice features that can help you:
POP_BACK_STACK_INCLUSIVE: Flag for popBackStack(String, int) and popBackStack(int, int): If set, and the name or ID of a back stack entry has been supplied, then all matching entries will be consumed until one that doesn't match is found or the bottom of the stack is reached.
and
popBackStack(int id, int flags) Pop all back stack states up to the one with the given identifier.
It seems that you want addToBackStack(null) for adding 2nd detail fragment, but not having addToBackStack(null) for adding 1st list fragment. Do you have addToBackStack(null) on 1st FragmentTransaction?
in my app contest i had the same problem on pressing back i was moving to previous fragment. But i want to close app on back press, so what i did is .
@Override
public void onBackPressed() {
finish();
// super.onBackPressed();
}
精彩评论