Android碎片:多项更改 - 应用程序崩溃

时间:2015-07-11 21:29:01

标签: android android-layout android-fragments android-activity

我有一个问题:我想用另一个片段替换一个片段。所以我写了这段代码:

    FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
    Fragment statistics = new Statistics();
    Fragment home = new Home();
    mTransaction.add(R.id.container, home);
    mTransaction.commitAllowingStateLoss();
    mTransaction.replace(R.id.container, statistics);
    mTransaction.commitAllowingStateLoss();

XML:

        <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        </LinearLayout>

问题是只有一个.commitAllowingStateLoss()调用正常,如果我这样做两次(如上所述)应用程序崩溃。不幸的是我需要多次调用它。这同样适用于.commit()。我究竟做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

因为在调用.commit ..之后,该事务被视为已关闭。 所以我认为你只需删除你的第一个名为.commit 所以代码将是

FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
Fragment statistics = new Statistics();
Fragment home = new Home();
mTransaction.add(R.id.container, home);
mTransaction.replace(R.id.container, statistics);
mTransaction.commitAllowingStateLoss();

如果您仍想要两次调用.commit,请在首次提交后开始另一个事务:

FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
Fragment statistics = new Statistics();
Fragment home = new Home();
mTransaction.add(R.id.container, home);
mTransaction.commitAllowingStateLoss();
mTransaction = getSupportFragmentManager().beginTransaction();
mTransaction.replace(R.id.container, statistics);
mTransaction.commitAllowingStateLoss();