2012年10月26日金曜日

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();
releaseInfoFragment 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.

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 use popBackStack() 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.

0 件のコメント:

コメントを投稿