我有片段说CompanyFragment,DashboardFragment,CalendarFragment。 我的默认片段是CompanyFragment。
预期流量
现在我在Fragment manager上添加了三个片段 CompanyFragment - > DashboardFragment - > CalenderFragment
我正在使用以下代码段来添加/替换片段
public void setFragmentToContainer(Fragment fragment) {
final String tag = fragment.getClass().getName();
if (manager == null) {
manager = getSupportFragmentManager();
}
transaction = manager.beginTransaction();
if (isFragmentInBackstack(manager, tag)) {
if (fragment instanceof DayPartStoreListingFragment) {
} else {
manager.popBackStackImmediate(tag, manager.POP_BACK_STACK_INCLUSIVE);
}
} else {
// Fragment doesn't exist
}
if (fragment instanceof CalenderFragment) {
transaction.setCustomAnimations(R.anim.slide_up, 0, 0, R.anim.slide_down);
}
if (fragment instanceof DayPartStoreListingFragment) {
transaction.add(R.id.layout_content, fragment, tag);
} else {
transaction.replace(R.id.layout_content, fragment, tag);
}
if (fragment instanceof CompanyLevelFragment) {
//Exit app on back press
} else {
transaction.addToBackStack(tag);
}
transaction.commit();
}
要检查fragmentmanager中的片段条目,我使用以下代码
public static boolean isFragmentInBackstack(final FragmentManager fragmentManager, final String fragmentTagName) {
for (int entry = 0; entry < fragmentManager.getBackStackEntryCount(); entry++) {
if (fragmentTagName.equals(fragmentManager.getBackStackEntryAt(entry).getName())) {
return true;
}
}
return false;
}
问题是: 当我尝试从CalendarFragment打开DashboardFragment时,第一次调用CompanyFragment的onResume,然后调用DashboardFragment onResume。 注意:我还没有从CalenderFragment调用CompanyFragment,CompanyFragments onResume在DashboardFragmet的onResume之前自动调用。同样的情况也发生在另一个片段上。在更改日期之后,首先调用先前片段的onResume,然后在请求的片段上调用onResume。
调试后我发现了问题 manager.popBackStackImmediate(tag,manager.POP_BACK_STACK_INCLUSIVE);
如果我从代码中删除此行,则上面的场景不会被复制。但我需要这一行来清除来自backstack的相同片段的旧条目。我真的需要帮助。
答案 0 :(得分:0)
步骤1:使用片段事务的添加方法未使用替换
node
步骤2:在片段的主要活动上写入onBAckPressed
FragSignUp FragSignUp = new FragSignUp();
FragmentTransaction ft = root.getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_right);
ft.addToBackStack(FragSignUp.class.getName());
ft.add(R.id.containerLogin, FragSignUp, FragSignUp.class.getName());
ft.commit();
可能是这段代码会工作试试吧......
答案 1 :(得分:0)
以下是有助于解决此问题的代码段
private void setFragmentToContainer(Fragment fragment) {
try {
String fragmentTag = fragment.getClass().getName();
manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(fragmentTag, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) { //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.layout_content, fragment, fragmentTag);
ft.addToBackStack(fragmentTag);
ft.commit();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}