Android – How to change fragments when navigation drawer item selected?

This is logical continuation to previous tutorial – Android – Material Design Navigation Drawer. If you have not done that tutorial, please open and implement what is written there.

In this tutorial, I will show how to change fragments when Material Design Navigation Drawer item selected.

This is also will be step by step tutorial:

Step 1: Add FrameLayout to activity_main.xml layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:orientation="vertical">

    <android.support.v7.widget.Toolbar
       android:id="@+id/toolbar"
       style="@style/HeaderBar"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="#BD601B"
       android:elevation="4dp"
       android:minHeight="?attr/actionBarSize"
       android:transitionName="actionBar"
       app:popupTheme="@style/ActionBarPopupThemeOverlay"
       app:theme="@style/ActionBarThemeOverlay" />

    <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:layout_weight="1"
       android:id="@+id/flFragments"/>

</LinearLayout>

Step 2: Create 3 Fragments(LibraryFragment, AddBookFragment, SettingsFragment). You can do it in this way: Right button of your mouse on your package(for example in my case it is net.joerichard.navigationdrawertutorial)->New->Fragment->Fragment(Blank). This will create you Fragment class with its layout. Now lets delete all methods of LibraryFragment besides onCreateView() method. After deleting, our LibraryFragment should something like this:

package net.joerichard.navigationdrawertutorial;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LibraryFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_library, container, false);
    }
   
}

And change background color of fragment_library.xml(to make sure we are changing fragments):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="net.joerichard.navigationdrawertutorial.LibraryFragment"
   android:background="#FF0000">

    <!-- TODO: Update blank fragment layout -->
    <TextView android:layout_width="match_parent" android:layout_height="match_parent"
       android:text="@string/hello_blank_fragment" />

</FrameLayout>

Do this step twice more for AddBookFragment and SettingsFragment!

Step 3: Last step is change fragment when user clicks on navigation drawer item. Where to put code to change fragments? We set onDrawerItemClickListener using withOnDrawerItemClickListener method. That’s why what we write our code inside that method calling. Inside onItemClick we put following code:

FragmentManager manager = getSupportFragmentManager();
                        FragmentTransaction transaction = manager.beginTransaction();
                        Fragment fragment = new Fragment();

                        switch (position)
                        {
                            case 0:
                                fragment = new LibraryFragment();
                                break;
                            case 1:
                                fragment = new AddBookFragment();
                                break;
                            case 2:
                                fragment = new SettingsFragment();
                                break;
                        }

                        transaction.replace(R.id.flFragments, fragment);
                        transaction.commit();

Final version of MainActivity should something like this:

package net.joerichard.navigationdrawertutorial;

import android.content.res.TypedArray;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;

import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.Nameable;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        DrawerBuilder builder = new DrawerBuilder()
                .withActivity(this)
                .withToolbar(toolbar)
                .addDrawerItems(
                        new SecondaryDrawerItem().withIcon(R.drawable.menu_icon1).withName(R.string.drawer_title1),
                        new SecondaryDrawerItem().withIcon(R.drawable.menu_icon2).withName(R.string.drawer_title2),
                        new SecondaryDrawerItem().withIcon(R.drawable.menu_icon3).withName(R.string.drawer_title3),
                        new SecondaryDrawerItem().withIcon(R.drawable.menu_icon4).withName(R.string.drawer_title4),
                        new SecondaryDrawerItem().withIcon(R.drawable.menu_icon5).withName(R.string.drawer_title5)
                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem) {

                        if (drawerItem != null) {
                            if (drawerItem instanceof Nameable) {
                                toolbar.setTitle(((Nameable)
                                        drawerItem).getNameRes());
                            }
                        }

                        FragmentManager manager = getSupportFragmentManager();
                        FragmentTransaction transaction = manager.beginTransaction();
                        Fragment fragment = new Fragment();

                        switch (position)
                        {
                            case 0:
                                fragment = new LibraryFragment();
                                break;
                            case 1:
                                fragment = new AddBookFragment();
                                break;
                            case 2:
                                fragment = new SettingsFragment();
                                break;
                        }

                        transaction.replace(R.id.flFragments, fragment);
                        transaction.commit();

                        return false;

                    }
                });

        Drawer drawer = builder.build();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

That’s it! Run your application and see the result!