Android:无法将一个片段替换为另一个

我需要将Fragment其中一个替换为Activity另一个Fragment,以下是的图层文件Activity:


<?xml version="1.0" encoding="utf-8"?>


<FrameLayout

  xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_width="fill_parent"

  android:layout_height="fill_parent"

  android:id="@+id/home_layout_container">


    <fragment android:name="com.foo.FragA"

        android:id="@+id/home_list"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent" />


    </FrameLayout>

所以默认情况下有FragA,现在我想在活动中将其替换为FragB,我这样做了:


public void onRegionClicked(Region region) {

    RegionInfoFragment rif = RegionInfoFragment.newInstance(region);

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

    ft.replace(R.id.home_list, rif);

}

但是我有一个例外:


>6:24:40.685: ERROR/AndroidRuntime(9194): Uncaught handler: thread main exiting due to uncaught exception

05-06 16:24:40.692: ERROR/AndroidRuntime(9194): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

05-06 16:24:40.692: ERROR/AndroidRuntime(9194):     at android.view.ViewGroup.addViewInner(ViewGroup.java:1857)

05-06 16:24:40.692: ERROR/AndroidRuntime(9194):     at android.view.ViewGroup.addView(ViewGroup.java:1752)

05-06 16:24:40.692: ERROR/AndroidRuntime(9194):     at android.view.ViewGroup.addView(ViewGroup.java:1709)

05-06 16:24:40.692: ERROR/AndroidRuntime(9194):     at android.view.ViewGroup.addView(ViewGroup.java:1689)

05-06 16:24:40.692: ERROR/AndroidRuntime(9194):     at android.support.v4.app.NoSaveStateFrameLayout.wrap(NoSaveStateFrameLayout.java:40)

05-06 16:24:40.692: ERROR/AndroidRuntime(9194):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:743)

05-06 16:24:40.692: ERROR/AndroidRuntime(9194):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:933)

05-06 16:24:40.692: ERROR/AndroidRuntime(9194):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:578)

我能做什么?


慕容708150
浏览 504回答 4
4回答

子衿沉夜

您不能替换在布局文件中静态定义的片段。您只能替换通过来动态添加的片段FragmentTransaction。

摇曳的蔷薇

尝试commit()在ft结束时,需要对commit()您的更改进行通知。

米脂

getFragmentManger()&nbsp; .beginTransaction&nbsp; .replace(R.id.frame,Yourfragment.newInstance(),null)&nbsp; .addtobackstack&nbsp; .commit();人们总是说我是一线客,所以这是您的一线客解决方案

小怪兽爱吃肉

将一个片段替换为另一个片段,并在后堆栈中保留先前的状态:&nbsp; &nbsp; // Create new fragment and transaction&nbsp; &nbsp; Fragment newFragment = new ExampleFragment();&nbsp; &nbsp; FragmentTransaction transaction = getFragmentManager().beginTransaction();&nbsp; &nbsp; // Replace whatever is in the fragment_container view with this fragment,&nbsp; &nbsp; // and add the transaction to the back stack&nbsp; &nbsp; transaction.replace(R.id.fragment_container, newFragment);&nbsp; &nbsp; transaction.addToBackStack(null);&nbsp; &nbsp; // Commit the transaction&nbsp; &nbsp; transaction.commit();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android