问题描述
我正在研究基于单一活动的原则.但是当再次打开相同的片段时,我遇到了一个问题,因为它再次添加了片段回栈条目.因此,backstack包含同一片段的多个backstack条目.这会在向后导航时产生问题.
I am working on single activity based principle. But I am facing a problem when the same fragment is open again because its again adds in fragment backstack entry. So backstack contains multiple backstack entries for same fragment. This creates problem on back navigation.
示例:-A | B | C | D | A | C | A
Example :- A|B|C|D|A|C|A
因此,当我按返回键时,同一片段会显示多次.有什么方法可以重用后退条目中的现有片段.
So when I press back key same fragment is displaying multiple times. Is there any way to reuse the existing fragment from backstack entry.
我正在像这样管理后台程序:-
I am managing my backstack like this :-
fragmentManager.beginTransaction().setCustomAnimations(R.anim.fragment_enter,
R.anim.fragment_exit, R.anim.pop_enter, R.anim.pop_exit).
add(R.id.frameLayout, fragment).addToBackStack(backStateName).commit();
任何帮助将不胜感激.
推荐答案
使用片段列表尝试
static List<String> fragments = new ArrayList<String>();
在活动"的第一个片段开始时添加
on Start of first fragment on Activity add this
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.frame, new AFragment()).commit();
fragments.add("package.fragment.AFragment");
}
String backStateName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
//fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
if(!fragments.contains(backStateName)) {
// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
// ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.replace(R.id.frame, fragment);
ft.addToBackStack(backStateName);
ft.commit();
fragments.add(backStateName);
System.out.println("backStateName" + fragments);
}
else
{
ft.replace(R.id.frame, fragment);
ft.commit();
}
@Override
public void onBackPressed() {
if(fragments.size()>0)
{
fragments.remove(fragments.size()-1);
}
super.onBackPressed();
}
final android.app.FragmentManager fm = getFragmentManager();
fm.addOnBackStackChangedListener(new android.app.FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() ==0) {
// dLayout.closeDrawers();
finish();
}
else
{
// dLayout.closeDrawers();
}
}
});
这篇关于单实例片段回栈管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!