getChildFragmentManager() on programmatically (dynamically) added Fragments?

后端 未结 2 1037
别那么骄傲
别那么骄傲 2020-12-12 16:24

How to use (or \"Can we use\") getChildFragmentManager() on programmatically (dynamically) added Fragments?

Here is my example.

相关标签:
2条回答
  • 2020-12-12 17:20

    In conclusion, I want to reference OuterFrag in MainActivity always. And I want OuterFrag act as a placeholder to load different InnerFrags. In short, I want to call getChildFragmentManager() in OuterFrag, when it is added programmatically (dynamically).

    If you want this then make your OuterFrag have a container layout as its content and add whatever InnerFrag to that container. The layout file for the OuterFrag will be:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />
    

    Of course you could have other views in the layout for the OuterFrag if you want that. Then your addInnerFrag method will be:

    public void addInnerFrag() {
            getChildFragmentManager().beginTransaction().add(R.id.fragContainer, new InnerFrag()).commit();
            getChildFragmentManager().executePendingTransactions();
    }
    

    The code for adding the OuterFrag to the main activity remains valid.

    0 讨论(0)
  • 2020-12-12 17:27

    If you want to call addInnerFrag() within your OuterFrag.java code, you can do it like this:

    OuterFrag.java:

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        addInnerFrag();
    }
    
    0 讨论(0)
提交回复
热议问题