gpt4 book ai didi

android - FragmentTransaction.remove 无效

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:16 24 4
gpt4 key购买 nike

我的要求很简单:我有一个按钮,应该用 FragmentB 替换 FragmentA。

这听起来很简单而且几乎可行,最大的问题是旧 fragment 没有被删除,新 fragment 放在旧 fragment 的前面,它们在我的布局中“生活”在一起。

enter image description here

代码:

FragmentManager fragMgr = a.getSupportFragmentManager();
Fragment currentFragment = (Fragment) fragMgr.findFragmentById(R.id.fragmentitself);

if(currentFragment!=null){

FragmentTransaction fragTrans = fragMgr.beginTransaction();
fragTrans.remove(currentFragment);

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();
}

布局:

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

<fragment
android:id="@+id/fragmentitself"
android:name="com.WazaBe.MyApp.FragmentA"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>

最佳答案

解决方案

首先,您必须从 XML 中删除您的 fragment 并只保留空容器:

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

然后您需要从代码中添加您的 com.WazaBe.MyApp.FragmentA fragment ,即在您的父 Activity 的 onCreate() 中。

解释

这是因为您的交易操纵了 ViewGroup 的内容,例如所说的 FrameLayouts。要注意的是,您只能操作从代码添加的元素,因为从 XML 布局扩展的任何内容都被视为“只读”。因此,当您将 Fragment 直接放入 XML 布局时,它就会成为 View 层次结构的永久部分,并且因为它是永久的并且整个层次结构是“只读的”,所以无法从代码中删除。

一旦您修复了布局并提取了 Fragment,就不再需要调用 remove() - 只需执行 replace() 就足够了。

关于android - FragmentTransaction.remove 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13323016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com