Android MainFragment中使用多个Fragment

本文解决了一个关于在MainFragment中添加多个Fragment时出现的问题,详细解释了如何正确使用getChildFragmentManager()来替代getSupportFragmentManager(),并避免因查找不存在的View而引发的异常。
摘要由CSDN通过智能技术生成

当前 MainFragment中创添加多个Fragment代码如下:

MainFragment的Layout文件main_dialog_fragment

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/ll_root_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:clickable="true"
    android:fitsSystemWindows="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">
        //...省略无关代码
        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white">
        </FrameLayout>
    </LinearLayout>
</LinearLayout>

MainFragment.Java文件如下:

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initParams();
        View rootView = inflater.inflate(R.layout.main_dialog_fragment, container, false);
        initFragments(savedInstanceState);
        return rootView;
    }
    
 //初始化两个Fragment 并且显示第一个
    private void initFragments(@Nullable Bundle savedInstanceState) {
        FragmentActivity fragmentActivity = getActivity();
        if (fragmentActivity == null) {
            return;
        }
        //savedInstanceState是对Bundle对象的引用,可以使用此捆绑包中存储的数据将自身恢复到以前的状态
        if (savedInstanceState == null) {
            try {
                //初始化Fragment
                m_fragment1 = new PaymentSubFragment1();
                m_fragment2 = new PaymentSubFragment2();
                
                fragmentActivity.getSupportFragmentManager().beginTransaction()
                        .add(R.id.fragment_container, m_fragment1, kTagFragment1)
                        .add(R.id.fragment_container, m_fragment2, kTagFragment2)
                        .detach(m_fragment2)
                        .commit();
            }catch (Exception e){
                Utils.printBBException(e,279);
            }
            //设定当前的Fragment,知道下一次hide那个Fragment
            m_CurFragment = m_fragment1;
        } else {
            //由于FragmentManager已经存在了这些Fragment直接获取就可以了
            m_fragment1 = (PaymentSubFragment1) fragmentActivity.getSupportFragmentManager()
                    .findFragmentByTag(kTagFragment1);
            m_fragment2 = (PaymentSubFragment2) fragmentActivity.getSupportFragmentManager()
                    .findFragmentByTag(kTagFragment2);
        }
    }

这时运行会报出如下错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.xxx.android, PID: 29708
    java.lang.IllegalArgumentException: No view found for id 0x7f08030b (com.xxx.android:id/fragment_container) for fragment PaymentSubFragment1{3820d34 (412762d8-5144-47fd-9ff7-abf3ce161066) id=0x7f08030b kTagFragment1}
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:875)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:264)
        at android.app.ActivityThread.main(ActivityThread.java:7581)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)

提示原因找不到View 名称为 fragment_container, 实际上Layout文件中是存在的,原因是在MainFragment中使用了getSupportFragmentManager方法,因为getSupportFragmentManager方法是属于FragmentActivity类的,因为查找的是Activity的Layout文件所以找不到这个View, 将其改为getChildFragmentManager就是当前MainFragment的Layout了,修改后代码如下:

    //初始化两个Fragment 并且显示第一个
    private void initFragments(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            try {
                //初始化Fragment
                m_fragment1 = new PaymentSubFragment1();
                m_fragment2 = new PaymentSubFragment2();

                getChildFragmentManager().beginTransaction()
                        .add(R.id.fragment_container, m_fragment1, kTagFragment1)
                        .add(R.id.fragment_container, m_fragment2, kTagFragment2)
                        .detach(m_fragment2)
                        .commit();
            }catch (Exception e){
                Utils.printBBException(e,279);
            }
            //设定当前的Fragment,知道下一次hide那个Fragment
            m_CurFragment = m_fragment1;
        } else {
            //由于FragmentManager已经存在了这些Fragment直接获取就可以了
            m_fragment1 = (PaymentSubFragment1) getChildFragmentManager()
                    .findFragmentByTag(kTagFragment1);
            m_fragment2 = (PaymentSubFragment2) getChildFragmentManager()
                    .findFragmentByTag(kTagFragment2);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xuanwenchao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值