无法使用popBackStack()或remove()

时间:2017-07-05 17:17:58

标签: android android-fragments fragment back-stack

我有2个片段: SportsList 锻炼

我将 SportsList 片段设为:

FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("SportsList").replace(R.id.fragment, sportsListFragment);

然后我将锻炼

FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("Workout").replace(R.id.fragment, workoutFragment);

我正在使用replace()方法,因此应删除 SportsList ,但当我致电popBackStackImmediate()时,它仍然存在。

因此,当我点击按钮时,我尝试在锻炼片段中手动删除 SportsList 。所以我这样做:

FragmentManager fm = getActivity().getSupportFragmentManager();
Fragment oldFragment = fm.findFragmentByTag("SportsList");
fm.beginTransaction().remove(oldFragment).commit();

但是这给了我以下错误:

  

致命的例外:主要                                                                               java.lang.NullPointerException:尝试在空对象引用上写入字段'int android.support.v4.app.Fragment.mNextAnim'                                                                                   在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:770)                                                                                   在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1682)                                                                                   在android.support.v4.app.FragmentManagerImpl $ 1.run(FragmentManager.java:541)                                                                                   在android.os.Handler.handleCallback(Handler.java:739)                                                                                   在android.os.Handler.dispatchMessage(Handler.java:95)                                                                                   在android.os.Looper.loop(Looper.java:135)                                                                                   在android.app.ActivityThread.main(ActivityThread.java:5254)                                                                                   at java.lang.reflect.Method.invoke(Native Method)                                                                                   在java.lang.reflect.Method.invoke(Method.java:372)                                                                                   在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903)                                                                                   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

我也试过这样做:

fm.popBackStack("SportsList", 0);

和此:

fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

和此:

fm.popBackStack("SportsList", FragmentManager.POP_BACK_STACK_INCLUSIVE);

但是这些正在删除当前片段(锻炼片段)而不是 SportsList 片段。我现在没有想法。除此之外:

ft.replace(R.id.fragment, sportsListFragment);

仍在向Backstack添加 SportsList 片段。怎么可能这样呢?

1 个答案:

答案 0 :(得分:0)

试试这个:

ft.addToBackStack("SportsList").replace(R.id.fragment, sportsListFragment).addToBackStack(null);