Android

Android Fragments With Navigation Drawer

navigation drawer with fragments
Written by Yasir Ameen

We can create adaptive layout using Fragments by dividing our Activity into groups, grouping does not mean dividing activity into pieces but overlapping a new layouts(fragments) on top of Activity. Fragment represents a portion of user interface in an Activity. Multi-pane UI can be easily created using Fragment. In this article i am going to create a simple app with Fragment using the Navigation Drawer.

 

Let’s Start With Android Fragments

Before doing anything let’s see what we are going to create.

In order to understand what fragment is, i tried to show in the following picture. In the following picture there are three apps, one is without fragment or you can say its an simple Activity, second one is Activity containing fragment and the third one is holding two fragments as layout inside an Activity.

understanding and creating a fragments

 

Creating a Fragment

you can create a fragment by following three easy steps, In the next picture you will see three steps you will need in order to create a fragment, then we will discuss these three steps.

creating a fragment in android

 

Creating Navigation Drawer Activity

Using the navigation drawer activity we can navigate different activity or fragments. The navigation drawer is a hidden panel most of the time but is revealed when user swipes a finger from left edge of the screen or by simply touching the app icon in the action bar.

  1. Create a blank project and name it Android Fragments
  2. Select Navigation Drawer Activity from Create New Project dialog click next and finish.

navigation drawer activity

 

important : i want you to run the app at this point in android emulator/device and see the results of Drawer Activity and click the app icon in the app bar to revealed hidden panel also notice the navigation menus available in the drawer, we will use these menus for calling Fragments.

 

Understanding Navigation Drawer Activity

When you select Navigation Drawer Activity for your project its create  four xml files in res=>layout folder, you dont need to go through all the files for creating a working drawer.  The content_main.xml file is important which we will use in our project.

  1. activity_main.xml
  2. app_bar_main.xml
  3. content_main.xml
  4. nav_header.xmll

Content of content_main.xml

This is inside content_main.xml file, if you want to override default layout with custom layout, then modify  other files according to your need, in this project i am happy with default layout 🙂

Navigation Drawer Content Main

Working With Drawer Menu

When you run the app and revealed navigation drawer, you see navigation menus also but these menus are not doing any action when you click. Let’s work with navigation drawer menu.

  1. Open activity_main_drawer.xml file available in res=>menu folder
  2. Download your favorite icon from here and paste into drawable directory [don’t use big icon size]
  3. Set icon by simply calling android:icon attribute. I’ll go with default.

 

android navigtion drawer menu

 

Content of activity_main_drawer.xml file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_camera"
            android:icon="@drawable/ic_menu_camera"
            android:title="Import" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="Send" />
        </menu>
    </item>

</menu>

 

Handling Click Event On Menus

To make Drawer Menus functional you use OnNavigationItemSelected() method inside in MainActivity.java file. We will create a fragment and call by calling these menu actions.

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

    if (id == R.id.nav_camera) {
        // Handle the camera Fragment
    
    } else if (id == R.id.nav_gallery) {
        // Handle the Gallery Fragment

    } else if (id == R.id.nav_slideshow) {
        // Handle the SlideShow Fragment

    } else if (id == R.id.nav_manage) {
        // Handle the Tools Fragment

    } else if (id == R.id.nav_share) {
        // Handle the Share Fragment

    } else if (id == R.id.nav_send) {
        // Handle the Send Fragment

    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

LET’S CREATE FRAGMENTS

Now you have an idea that where we will use fragments, using a fragments in Navigation Drawer Activity is a good approach. We will create fragment according to the menus available in Navigation Drawer.

Creating Camera Import Fragment

Step 1) Creating an XML Layout file for fragment.

  1. Create an xml layout file in res=>layout folder and name it camera_import_fragment.xml and paste the following xml code.
  2. I am using images in every fragment layout, you can download these images from here

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/imageView2"
        android:tint="#999999"
        android:src="@drawable/ic_camera_alt_black_48dp"
        android:layout_marginTop="100dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Camera Import Fragment"
        android:textColor="#999999"
        android:layout_marginTop="20dp"
        android:id="@+id/textView2"
        android:gravity="center_horizontal"
        android:layout_below="@+id/imageView2"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

 

above xml will generate following output

 

android camera import fragment

Step 2) Creating Java Class For Extending Fragment.

  1. Create a java class and call it CameraImportFragment.java and extend it android.support.v4.app.Fragment class because we want backward compatibility.
  2. Override on OnCreatView() method inside CameraImportFragment.java class



public class CameraImportFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.camera_import_fragment,container,false);

        /* Define Your Functionality Here
           Find any view  => v.findViewById()
          Specifying Application Context in Fragment => getActivity() */

        return v;
    }
}

 

Adding a Camera Import Fragment To An MainActivity

Step a) Adding FrameLayout in content_main.xml file

If you notice there is only one Activity in our project which is MainActivity.java. We will use that activity for holding all the fragments we create. Now its time to implement CameraImportFragment

  1. Open content_main.xml and remove everything.
  2. And Paste the following xml code.
  3. Remember the id of FrameLayout in your mind.
  4. All the fragment will be place inside a FrameLayout in MainActivty.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_frame"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context=".MainActivity">


</FrameLayout>

 

Step b) Putting It All Together

Now its time to call CameraImportFragment when you click import menu from the Navigation Drawer Menu.

  1. Open MainActivity.java file and look for the OnNavigationItemSelected() method.
  2. Paste the following code when user click R.id.nav_camera
  3. Run the application and click Import Menu from the Navigation Drawer Menu

 


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

    if (id == R.id.nav_camera) {
        
        CameraImportFragment cameraImportFragment = new CameraImportFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame,cameraImportFragment)
                .addToBackStack(null)
                .commit();

    } else if (id == R.id.nav_gallery) {
        // Handle the Gallery Fragment

    } else if (id == R.id.nav_slideshow) {
        // Handle the SlideShow Fragment

    } else if (id == R.id.nav_manage) {
        // Handle the Tools Fragment

    } else if (id == R.id.nav_share) {
        // Handle the Share Fragment

    } else if (id == R.id.nav_send) {
        // Handle the Send Fragment

    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Run the app and you will see the results look like in Video.

 

Create => Repeat => Implement

You have successfully called a fragment inside MainActivity, Now its time to assemble all fragments into one place, Its is very easy to do it. Just repeat the step we use previously for creating CameraImportFragment.

  1. Create a Xml Layout file for gallery_fragment.xml
  2. Create a Java class and name it GalleryFragment.java extend it to android.support.v4.app.Fragment class
  3. public class GalleryFragment extends Fragment {
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
            View v = inflater.inflate(R.layout.gallery_fragment,container,false);
    
            /* Define Your Functionality Here
               Find any view  => v.findViewById()
              Specifying Application Context in Fragment => getActivity() */
    
            return v;
        }
    }
    
  4. Now add GalleryFragment inside OnNavigationItemSelected() method when user click gallery(R.id.nav_gallery) by pasting following code
  5. GalleryFragment galleryFragment = new GalleryFragment();
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.content_frame,galleryFragment)
            .addToBackStack(null)
            .commit();
    
  6. Repeat Step 1 to 5 for creating and calling other fragments.

 

Complete Code Of OnNavigationItemSelected() method

Here is the complete working code, handling all the fragments we just created. You can paste/write following code in MainActivity.java.


@SuppressWarnings(&amp;quot;StatementWithEmptyBody&amp;quot;)
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {

        CameraImportFragment cameraImportFragment = new CameraImportFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame,cameraImportFragment)
                .addToBackStack(null)
                .commit();

    } else if (id == R.id.nav_gallery) {

        GalleryFragment galleryFragment = new GalleryFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame,galleryFragment)
                .addToBackStack(null)
                .commit();
    } else if (id == R.id.nav_slideshow) {

        SlideShowFragment slideShowFragment = new SlideShowFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame,slideShowFragment)
                .addToBackStack(null)
                .commit();

    } else if (id == R.id.nav_manage) {

        ToolsFragment toolsFragment = new ToolsFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame,toolsFragment)
                .addToBackStack(null)
                .commit();

    } else if (id == R.id.nav_share) {

        ShareFragment shareFragment = new ShareFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame,shareFragment)
                .addToBackStack(null)
                .commit();

    } else if (id == R.id.nav_send) {

        SendFragment sendFragment = new SendFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame,sendFragment)
                .addToBackStack(null)
                .commit();

    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Run the app and see the results look like in video.

 

 

Sliding Animation In Fragments

Great! Now you have working example of Navigation Drawer Activity implemented Fragments, but fragment appearing and disappearing instantaneously, that is not good for the user experience. We will add animation when user back and forth in between fragments.

  1. Create a resource directory called anim in res folder.
  2. Create Animation resource file in res=>anim, name it enter.xml and paste the following code.
  3. <?xml version="1.0" encoding="utf-8"?>
    <set>
        <translate xmlns:android="http://schemas.android.com/apk/res/android"
            android:fromXDelta="100%"
            android:toXDelta="0"
            android:interpolator="@android:anim/decelerate_interpolator"
            android:duration="@android:integer/config_mediumAnimTime"/>
    </set>
    
  4. Create Animation resource file in res=>anim, name it exit.xml and paste the following code.
  5. <?xml version="1.0" encoding="utf-8"?>
    <set>
        <translate xmlns:android="http://schemas.android.com/apk/res/android"
            android:fromXDelta="0"
            android:toXDelta="-100%"
            android:interpolator="@android:anim/accelerate_interpolator"
            android:duration="@android:integer/config_mediumAnimTime"/>
    </set>
    
  6. Create Animation resource file in res=>anim, name it pop_enter.xml and paste the following code.
  7. <?xml version="1.0" encoding="utf-8"?>
    <set>
        <translate xmlns:android="http://schemas.android.com/apk/res/android"
            android:fromXDelta="-100%"
            android:toXDelta="0"
            android:interpolator="@android:anim/decelerate_interpolator"
            android:duration="@android:integer/config_mediumAnimTime"/>
    </set>
    
  8. Create Animation resource file in res=>anim, name it pop_exit.xml and paste the following code.
  9. <?xml version="1.0" encoding="utf-8"?>
    <set>
        <translate xmlns:android="http://schemas.android.com/apk/res/android"
            android:fromXDelta="0"
            android:toXDelta="100%"
            android:interpolator="@android:anim/accelerate_interpolator"
            android:duration="@android:integer/config_mediumAnimTime"/>
    </set>
    
  10. Animation Resources is created successfully now its time to implement it 🙂

 

Implementing Animation To The Fragments

Applying animation to fragment is very easy, you just need to add one line after .beginTransaction() mehod. Add the following highlighted line in every fragment you are replacing in OnNavgationItemSeletect() method inside MainActivity.java.

adding sliding animation to the fragment

 

Run the app and you will see nice sliding animation when changing Fragments like i did.

 

Customizing Navigation Drawer

There are different application available on PlayStore in which we see good and appealing design of Navigation Drawer. We will override the default layout of Navigation Drawer with our custom design.

Customizing Navigation Drawer is little bit tricky, we create our own layout and rplace the newly created layout with default one.

  1. Create a layout resources file, call it nav_panel_layout.xml and paste following xml, I am using circular image in following layout
  2. <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <ImageView
            android:id="@+id/header_img"
            android:layout_width="match_parent"
            android:layout_height="180dp"
            android:scaleType="centerCrop"
            android:src="@drawable/nav_header_bg"/>
    
        <com.pkmmte.view.CircularImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:id="@+id/avatar"
            android:src="@drawable/mydp"
            app:border="true"
            android:scaleType="centerCrop"
            app:border_color="#212121"
            app:border_width="4dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="25dp" />
    
        <ListView
            android:id="@+id/list"
            android:divider="#ffffff"
            android:paddingBottom="10dp"
            android:layout_width="match_parent"
            android:layout_height="270dp"
            android:layout_below="@id/header_img"
            android:layout_above="@+id/bottom_bar">
    
        </ListView>
    
        <LinearLayout
            android:id="@+id/bottom_bar"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:src="@drawable/nav_header_bg"/>
    
    
        </LinearLayout>
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="YASIR AMEEN"
            android:textColor="#000000"
            android:id="@+id/textView"
            android:layout_below="@+id/avatar"
            android:layout_centerHorizontal="true" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="YasirAmeen92@Gmail.com"
            android:textColor="#000000"
            android:id="@+id/textView3"
            android:layout_below="@+id/textView"
            android:layout_centerHorizontal="true" />
    
    </RelativeLayout>
    
  3. Output of above xml will be look like this.
  4. navigation panel layout
  5. Now create another layout resource file call it nav_list_template.xml and pase the following xml, this will be use for customize listview with images.
  6. <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:id="@+id/menu_img"
            android:paddingBottom="2dp"
            android:src="@drawable/import_camera"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="21dp"
            android:layout_marginStart="21dp"
            android:layout_marginTop="23dp" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Camera Import"
            android:id="@+id/mene_id"
            android:paddingBottom="4dp"
            android:layout_marginBottom="2dp"
            android:layout_marginLeft="20dp"
            android:layout_marginStart="20dp"
            android:layout_alignBottom="@+id/menu_img"
            android:layout_toRightOf="@+id/menu_img"
            android:layout_toEndOf="@+id/menu_img" />
    </RelativeLayout>
    
  7. Output of above code will display a list item look like this,
  8. navigation list item template
  9. Lastly create a java class and name it NavPanelListAdapter.java and paste the follwoing code. This is an adapter class for implementing customize listview in Navigation Drawer.
  10.  public class NavPanelListAdapter extends BaseAdapter{
    
        private Context context;
        private LayoutInflater inflater = null;
    
        String[] menus = {&quot;Import&quot;,&quot;Gallery&quot;,&quot;Slideshow&quot;,&quot;Tools&quot;,&quot;Share&quot;,&quot;Send&quot;};
        int[] menuImg = {
    
                R.drawable.import_camera,
                R.drawable.gallery_nav,
                R.drawable.slideshow_nav,
                R.drawable.tools_nav,
                R.drawable.share_nav,
                R.drawable.send_nav
    
        };
        
         NavPanelListAdapter(Context con, String[] menus) {
    
            this.context = con;
            menus = menus;
            inflater = LayoutInflater.from(context);
        }
        
        @Override
        public int getCount() {
            return menus.length;
        }
    
        @Override
        public Object getItem(int i) {
            return menus.length;
        }
    
        @Override
        public long getItemId(int i) {
            return i;
        }
    
        @Override
        public View getView(int i, View convertview, ViewGroup viewGroup) {
            ViewHolder holder;
            if(convertview == null) {
    
                convertview =inflater.inflate(R.layout.nav_list_template,null);
                holder = new ViewHolder();
                holder.imgMenu = (ImageView) convertview.findViewById(R.id.menu_img);
                holder.txtMenu = (TextView) convertview.findViewById(R.id.mene_id);
                convertview.setTag(holder);
    
            } else {
                holder = (ViewHolder) convertview.getTag();
            }
    
            holder.txtMenu.setText(menus[i]);
            holder.imgMenu.setImageResource(menuImg[i]);
            return convertview;
        }
    
        public class ViewHolder {
    
            ImageView imgMenu;
            TextView txtMenu;
    
        }
    }
    
  11. Yeah! you have created all the resources for implementing customize Navigation Drawer, now its time to fire it.

 

Let’s Apply Custom Layout To The Navigation Drawer

Step 1) Open activity_main.xml remove every thing and paste following xml code

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true">

        <include
            layout="@layout/nav_panel_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

Step 2) Now Open MainActivity.java and paste the following code below highlighted text

android customize navigation bar

//CustomAdapter we created for Customize Navigation
ListView navlist = (ListView) findViewById(R.id.list);
NavPanelListAdapter adapter = new NavPanelListAdapter(this,menus);
navlist.setAdapter(adapter);

navlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        String selectedMenu = menus[i];

        switch (selectedMenu) {

            case "Import":
                CameraImportFragment cameraImportFragment = new CameraImportFragment();
                getSupportFragmentManager().beginTransaction()
                        .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                        .replace(R.id.content_frame,cameraImportFragment)
                        .addToBackStack(null)
                        .commit();
                break;

            case "Gallery":
                GalleryFragment galleryFragment = new GalleryFragment();
                getSupportFragmentManager().beginTransaction()
                        .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                        .replace(R.id.content_frame,galleryFragment)
                        .addToBackStack(null)
                        .commit();
                break;

            case "Slideshow":
                SlideShowFragment slideShowFragment = new SlideShowFragment();
                getSupportFragmentManager().beginTransaction()
                        .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                        .replace(R.id.content_frame,slideShowFragment)
                        .addToBackStack(null)
                        .commit();
                break;

            case "Tools":
                ToolsFragment toolsFragment = new ToolsFragment();
                getSupportFragmentManager().beginTransaction()
                        .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                        .replace(R.id.content_frame,toolsFragment)
                        .addToBackStack(null)
                        .commit();
                break;

            case "Share":
                ShareFragment shareFragment = new ShareFragment();
                getSupportFragmentManager().beginTransaction()
                        .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                        .replace(R.id.content_frame,shareFragment)
                        .addToBackStack(null)
                        .commit();
                break;

            case "Send":
                SendFragment sendFragment = new SendFragment();
                getSupportFragmentManager().beginTransaction()
                        .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                        .replace(R.id.content_frame,sendFragment)
                        .addToBackStack(null)
                        .commit();
                break;

            default:
                break;



        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);


    }
});

 

Run the app and enjoye 🙂

 

FULL CODE OF MainActivity.java CLASS


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        final String[] menus = {"Import","Gallery","Slideshow","Tools","Share","Send"};

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
        navigationView.setNavigationItemSelectedListener(this);

        //CustomAdapter we created for Customize Navigation
        ListView navlist = (ListView) findViewById(R.id.list);
        NavPanelListAdapter adapter = new NavPanelListAdapter(this,menus);
        navlist.setAdapter(adapter);

        navlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String selectedMenu = menus[i];

                switch (selectedMenu) {

                    case "Import":
                        CameraImportFragment cameraImportFragment = new CameraImportFragment();
                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame,cameraImportFragment)
                                .addToBackStack(null)
                                .commit();
                        break;

                    case "Gallery":
                        GalleryFragment galleryFragment = new GalleryFragment();
                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame,galleryFragment)
                                .addToBackStack(null)
                                .commit();
                        break;

                    case "Slideshow":
                        SlideShowFragment slideShowFragment = new SlideShowFragment();
                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame,slideShowFragment)
                                .addToBackStack(null)
                                .commit();
                        break;

                    case "Tools":
                        ToolsFragment toolsFragment = new ToolsFragment();
                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame,toolsFragment)
                                .addToBackStack(null)
                                .commit();
                        break;

                    case "Share":
                        ShareFragment shareFragment = new ShareFragment();
                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame,shareFragment)
                                .addToBackStack(null)
                                .commit();
                        break;

                    case "Send":
                        SendFragment sendFragment = new SendFragment();
                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame,sendFragment)
                                .addToBackStack(null)
                                .commit();
                        break;

                    default:
                        break;



                }

                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                drawer.closeDrawer(GravityCompat.START);


            }
        });

        }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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);
    }

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

        if (id == R.id.nav_camera) {

            CameraImportFragment cameraImportFragment = new CameraImportFragment();
            getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                    .replace(R.id.content_frame,cameraImportFragment)
                    .addToBackStack(null)
                    .commit();

        } else if (id == R.id.nav_gallery) {

            GalleryFragment galleryFragment = new GalleryFragment();
            getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                    .replace(R.id.content_frame,galleryFragment)
                    .addToBackStack(null)
                    .commit();
        } else if (id == R.id.nav_slideshow) {

            SlideShowFragment slideShowFragment = new SlideShowFragment();
            getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                    .replace(R.id.content_frame,slideShowFragment)
                    .addToBackStack(null)
                    .commit();

        } else if (id == R.id.nav_manage) {

            ToolsFragment toolsFragment = new ToolsFragment();
            getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                    .replace(R.id.content_frame,toolsFragment)
                    .addToBackStack(null)
                    .commit();

        } else if (id == R.id.nav_share) {

            ShareFragment shareFragment = new ShareFragment();
            getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                    .replace(R.id.content_frame,shareFragment)
                    .addToBackStack(null)
                    .commit();

        } else if (id == R.id.nav_send) {

            SendFragment sendFragment = new SendFragment();
            getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                    .replace(R.id.content_frame,sendFragment)
                    .addToBackStack(null)
                    .commit();

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

 

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

6 Comments

Leave a Comment