Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

android - Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

I'm using the Android Compatibility library to implement fragments and have extended the layout sample so that a fragment contains a button which fires off another fragment.

In the selection pane on the left I have 5 selectable items - A B C D E.

Each loads up a fragment (via FragmentTransaction:replace) in the details pane - a b c d e

Now I've extended fragment e to contain a button which loads up another fragment e1 also in the details pane. I've done this on fragment e's onClick method as follows:

FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.details_frag, newFrag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();

If I make the following selections:

E - e - e1 - D - E

Then fragment e is in the details pane. This is fine and what I want. However, if I hit the back button at this point it does nothing. I have to click it twice because e1 is still on the stack. Furthermore after clicking around I got a null pointer exception in onCreateView:

To 'solve' this problem I added the following whenever A B C D E is selected:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
    fm.popBackStack();
}

Just wondering whether this is the correct solution or whether I should be doing something different?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well there are a few ways to go about this depending on the intended behavior, but this link should give you all the best solutions and not surprisingly is from Dianne Hackborn

http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42

Essentially you have the following options

  • Use a name for your initial back stack state and use FragmentManager.popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE).
  • Use FragmentManager.getBackStackEntryCount()/getBackStackEntryAt().getId() to retrieve the ID of the first entry on the back stack, and FragmentManager.popBackStack(int id, FragmentManager.POP_BACK_STACK_INCLUSIVE).
  • FragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) is supposed to pop the entire back stack... I think the documentation for that is just wrong. (Actually I guess it just doesn't cover the case where you pass in POP_BACK_STACK_INCLUSIVE),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...