Search code examples
androidandroid-fragmentsdrawerlayout

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 MainLayout by FragmentTransaction.

public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.home) {
        FragmentTransaction transaction = manager.beginTransaction();
        Hello f1 = new Hello();
        transaction.replace(R.id.main_layout,f1,"home");
        transaction.commit();

    }

Up to this point, the project runs without problems. But, I need to put Fragment inside an item's Fragment (nested Fragment). The Fragment of item already has a fragment inside of it, so how can I do this?


Solution

  • 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:

    public class HostFragment extends Fragment {
    private Fragment hostedFragment;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.host_fragment, container, false);
        if (hostedFragment != null) {
            replaceFragment(hostedFragment);
        }
        return view;
    }
    
    public void replaceFragment(Fragment fragment) {
        getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).commit();
    }
    
    public static HostFragment newInstance(Fragment fragment) {
        HostFragment hostFragment = new HostFragment();
        hostFragment.hostedFragment = fragment;
        return hostFragment;
    }
    

    }

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

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns: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.