Skip to content Skip to sidebar Skip to footer

Create A Nested Fragment

I have MainLayout which contains multiple instances of DrawerLayout, each Drawerlayout has 3 items and every item has a fragment. When I click on an item its fragment displays on M

Solution 1:

You can nest a fragment inside another fragment using the host fragment's child fragment manager. An example setup can look like this:

HostFragment.java, a host fragment that hosts an arbitrary fragment:

publicclassHostFragmentextendsFragment {
private Fragment hostedFragment;

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    Viewview= inflater.inflate(R.layout.host_fragment, container, false);
    if (hostedFragment != null) {
        replaceFragment(hostedFragment);
    }
    return view;
}

publicvoidreplaceFragment(Fragment fragment) {
    getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).commit();
}

publicstatic HostFragment newInstance(Fragment fragment) {
    HostFragmenthostFragment=newHostFragment();
    hostFragment.hostedFragment = fragment;
    return hostFragment;
}

}

host_fragment.xml, the layout inflated by the HostFragment class:

<?xml version="1.0" encoding="utf-8"?><FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/hosted_fragment" ></FrameLayout>

If you also need separate back navigation for each HostFragment, refer to this tutorial I've written about a similar situation with a ViewPager. Hopefully you can adapt the tutorial to your situation. Also refer to this and this section of codepath's guide about fragments.

Post a Comment for "Create A Nested Fragment"