How to use (or \"Can we use\") getChildFragmentManager()
on programmatically (dynamically) added Fragment
s?
Here is my example.
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.
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();
}