FragmentTransaction.remove has no effect

北慕城南 提交于 2019-12-03 12:25:14

Solution

First, you have to remove your fragment from XML and just keep empty container there:

<FrameLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2" 
    android:id="@+id/fragmentcontainer" />

Then you need to add your com.WazaBe.MyApp.FragmentA fragment from code, i.e. in onCreate() of your parent Activity.

Explanation

It is because your transactions manipulate content of ViewGroup such as said FrameLayouts. The catch is, that you can only manipulate elements you added from code. So when you put your Fragment directly into your XML layout, then it becomes permanent part of the View hierarchy and because it is permanent, it cannot be removed from code.

Once you get your layout fixed and Fragment extracted, the remove() call is no longer needed - it will suffice to just do replace().

If you want to place a Fragment in a View Container(Such as a Framelayout),you must make sure that your container is empty(only this you can put a fragment into it).you cannot replace a fragment writed in XML file,you should add A into the container by JAVA code ,and when you don't neet id ,you can replace it by B;

at first ,your container is empyt:

<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" 
android:id="@+id/fragmentcontainer">
</FrameLayout>

OK,you put FragmentA into it:

 FragmentTransaction fragTrans = fragMgr.beginTransaction();
 fragTrans.remove(currentFragment);
 FragmentA fragA= new FragmentA();
 fragTrans.add(R.id.fragmentcontainer, fragA).commit();

NOW,if you want to replace:

FragmentTransaction fragTrans = fragMgr.beginTransaction();
 FragmentB newFragment = new FragmentB();
 fragTrans.replace(R.id.fragmentcontainer, newFragment);
 // I have also tried with R.id.fragmentitself
 fragTrans.addToBackStack(null);
 fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
 fragTrans.commit();

if we use Fragment container on activity, it require select one default FragmentABC, the default FragmentABC view cannot removed even we use the ft.remove.

Use FrameLayout container instead of Fragment container if you want a empty view of fragment on activity startup.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!