您将需要添加一个方法来将片段推送到后台堆栈或弹出项目,以便我们可以重用已经在后台堆栈中的片段。以下函数中的“名称”参数提供了定位和弹回的最佳方式(如果需要)
private void popToOrPushFragmentWithName(Fragment fragment, String name, FragmentTransaction ft) {
FragmentManager manager = getSupportFragmentManager();
// Scan the back stack for an entry with the given fragment name
int count = manager.getBackStackEntryCount();
FragmentManager.BackStackEntry entry = null;
while (--count >= 0) {
FragmentManager.BackStackEntry check = manager.getBackStackEntryAt(count);
if (check.getName() != null && check.getName().equals(name)) {
entry = check;
break;
}
}
if (entry == null) {
// There is no entry, so push the fragment
ft.replace(R.id.fragment_container, fragment);
ft.addToBackStack(name);
// might not need this next line (since you are using tabselected override)
ft.commit();
} else {
// Pop back to the existing fragment (0 = not inclusive, so our fragment by index is on top)
manager.popBackStackImmediate(entry.getId(), 0);
}
}
您的 onTabselected 应如下所示:
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
FragmentA frag = new FragmentA();
popToOrPushFragmentWithName(frag, "FragmentA", ft);
}
else
{
FragmentB frag = new FragmentB();
popToOrPushFragmentWithName(frag, "FragmentB", ft);
}
}
我希望这有帮助。:)