防止同一个片段堆叠多次(addToBackStack) [英] Prevent The Same Fragment From Stacking More Than Once ( addToBackStack)
问题描述
我有一个 Activity
,其中有三个Fragments,可以称它们为 A , B 和 C < STRONG>。在Activity onCreate()
中调用 Fragment A 。
I have an Activity
with three Fragments lets call them A, B and C. Fragment
A is called in the Activity onCreate()
.
FragmentA fragA = new FragmentA();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.activity2_layout, fragA, "A");
transaction.commit();
然后被碎片 B 或 C 当某些按钮被按下,FragmentTransaction调用 addToBackStack()
。
And gets replaced with Fragment B or C when certain buttons are pressed, and the FragmentTransaction calls addToBackStack()
.
FragmentB fragB = new FragmentB(); //or C
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.activity2_layout, fragB, "B"); //or C
transaction.addToBackStack("B"); //or C
transaction.commit();
但是可以说我称之为 Fragment
B 连续三次,我怎样才能防止它叠加到它自己?同时我希望这可以: B 调用> C 调用> B 调用 - 但是当我尝试返回时要将 B 仅打开一次( C < B )而不是( B
But lets say I call Fragment
B three times in a row, how can I prevent it from stacking on to it self? And at the same time I want this to be possible: B called > C called > B called - BUT when i try to go back I want B to be opened only once ( C < B) instead of (B < C < B). So basically removing the first backStack with the new one.
推荐答案
From 如何从BackStack恢复Fragment(如果存在),这可能与您的查询非常相似。
From How to resume Fragment from BackStack if exists, which maybe very similar to your query.
有一种方法可以将背面基于提交的事务名或ID提供的堆栈(例如,使用Fragment的类名作为
Thijs已经提到的):
There is a way to pop the back stack based on either the transaction name or the id provided by commit (for eg. using the Fragment's class name as Thijs already mentioned):
String backStateName = fragment.getClass().getName();
添加到后台:
Adding to backstack:
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(backStateName);
ft.commit();
出现时:
When popping:
getSupportFragmentManager().popBackStackImmediate (backStateName, 0);
因此,在替换fragment之前,我们可以检查backstack中的存在如:
So before replacing fragment, we can check existance in backstack like:
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped){ //fragment not in back stack, create it.
...
...
ft.addToBackStack(backStateName);
ft.commit();
}
请查看以上问题和接受的答案以获得更多解释。
Please check the above question and the accepted answer for more explanation.
这篇关于防止同一个片段堆叠多次(addToBackStack)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!