How to use navigation drawer activity in Android Studio

[This post was updated on 13-03-2017 ]

We will show you the correct way of creating navigation drawer in android .

1.  We will deal with error cause by : onFragmentInteraction

2. Set a drawer element selected by default.

3. Change toolbar title based on active fragment.

NUTSHELL:-

  1. We have started to use Fragments instead of Activities. ( in short, fragments are light weight)
  2. To create Fragments in your main project  i.e Right click on the project folder -> New -> Fragments -> Fragment (Blank).
  3.  <FrameLayout> </FrameLayout> is used as a container for Fragments
  4. Code for Fragment Switching:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, new Fragment1());
ft.commit();

 

NAVIGATION DRAWER ACTIVITY

[wpi_designer_button text=’Download’ link=’https://github.com/arjunsk/android_navigation_drawer&#8217; style_id=’48’ icon=’github’ target=’_blank’]

INTRO :-

  1. Create a new Android Project  ->  Minimum SDK: 15  -> Navigation Drawer Activity -> Finish.

How to use navigation layout activity in android studio

2. Now let us examine the files that are automatically generated by Android studio.

Layout Folder:

  • content_main.xml : This is basically the First Screen i.e initially it contains only a TextView with Hello World!!We will replace the inner content with <frame-layout> , so that we can display our fragments.

content_main.xml

  • app_bar_main.xml: Contains the Toolbar overlay and Floating button.

app_bar_main.xml

  • nav_header_main.xml: Contains a part of navigation drawer.

nav_header_main.xml

  • activity_main.xml: Links  app_bar_main  &  nav_header_main (the menu items are added from menu/activity_main_drawer.xml )

Menu Folder:

  • menu/main.xml: Contains the menu items for App Tool Bar (By default it will contain only settings)

menu/main.xml

  • menu/activity_main_drawer.xml : Contains the menu items for navigation drawer.

Java Package Folder:

MainActivity.java : The main java file where you write the code (Basically onClickListeners  for navigation drawer menus and Tool bar menus.)

 

STEPS :-

1. Hope you have already created a navigation drawer project.

2. Create a new Fragment. Name it as Fragment 1.

3. Create 2 other fragments. Name them as Fragment2  and Fragment3.

4. Open content_main.xml and replace the inner textfield with framelayout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.arjunsk.fragments_2.MainActivity"
tools:showIn="@layout/app_bar_main">

    <!-- Note : This is the container Frame Layout for all the fragmetns-->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mainFrame">
    </FrameLayout>

</android.support.constraint.ConstraintLayout>

5. Since we have created only three fragments, we will modify the drawer menu, so that it displays only three options.

Goto : res > menu > activity_main_drawer.xml . Replace its contents with the following

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

    <!-- Note:  android:checkableBehavior="single" -->
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_frag1"
            android:icon="@drawable/ic_menu_camera"
            android:title="Fragment 1" />
        <item
            android:id="@+id/nav_frag2"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Fragment 2" />
        <item
            android:id="@+id/nav_frag3"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Fragment 3" />

    </group>

</menu>

6. Now comes the MainActivity.java .

(1) In the onCreate() add the following to the end of the function.

       //NOTE:  Checks first item in the navigation drawer initially
        navigationView.setCheckedItem(R.id.nav_frag1);

        //NOTE:  Open fragment1 initially.
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.mainFrame, new Fragment1());
        ft.commit();

 

(2) Replace onNavigationItemSelected()

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        //NOTE: creating fragment object
        Fragment fragment = null;

        if (id == R.id.nav_frag1) {
            fragment = new Fragment1();
        } else if (id == R.id.nav_frag2) {
            fragment = new Fragment2();
        }else if (id == R.id.nav_frag3) {
            fragment = new Fragment3();
        }

        //NOTE: Fragment changing code
        if (fragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.mainFrame, fragment);
            ft.commit();
        }

        //NOTE:  Closing the drawer after selecting
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); //Ya you can also globalize this variable 😛
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

 

(3) In the extends AppCompactActivity implements part , add the OnFragmentInteractionListener for all the 3 fragments.

public class MainActivity extends AppCompatActivity


        //Note : OnFragmentInteractionListener of all the fragments
        implements
        Fragment1.OnFragmentInteractionListener,
        Fragment2.OnFragmentInteractionListener,
        Fragment3.OnFragmentInteractionListener,

        NavigationView.OnNavigationItemSelectedListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {

 

(4) Now un/fortunately you will be seeing a whole bunch of red underlinings. Dont worry, press Alt + Enter and resolve the error by auto implementing onFragmentInteraction()

Why do we need it ? Basically, I use to set the toolbar title when i toggle between different fragments.

So let modify it accordingly.

    @Override
    public void onFragmentInteraction(String title) {
        // NOTE:  Code to replace the toolbar title based current visible fragment
        getSupportActionBar().setTitle(title);
    }

We are done with the MainAcitivity.java

7. We will now open Fragment1.java. There is hell alot of boiler plate code in there.

Just to give a brief overview. ( Deviating from the main course)

  • public static Fragment1 newInstance() is use for creating fragment objects passing some parameters.
  • public void onCreate() is used for initializing/doing some non graphical things. For eg:- Initializing firebase database, or gps object. ( Do not use include functions that will modify the android screen here. It will bring crashes, as view object is created.)
  • onAttach() is called when fragment 1 is currently being displayed. For eg:- You can start the locationChangeListner() for map in case, you are view the map fragment.
  • onDetach() is called when fragment 1 is now removed from the displayed view. You can pause locationChangeListner() as you don’t need to update the data into map, when you are not looking at the map fragment.
  • onBackPressed() just remove it 😛
  • onCreateView() is the part where fragments view is set, ie the GUI part of fragment.  (Coming back to the main course)
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            View view= inflater.inflate(R.layout.fragment_fragment1, container, false);
            
            // NOTE : We are calling the onFragmentInteraction() declared in the MainActivity
            // ie we are sending "Fragment 1" as title parameter when fragment1 is activated
            if (mListener != null) {
                mListener.onFragmentInteraction("Fragment 1");
            }
    
            // Here we will can create click listners etc for all the gui elements on the fragment.
            // For eg: Button btn1= (Button) view.findViewById(R.id.frag1_btn1);
            // btn1.setOnclickListener(...
    
            return view;
        }
    
  • OnFragmentInteractionListener() we will pass the needed title for fragment to MainActivity here.

       public interface OnFragmentInteractionListener {
           // NOTE : We changed the Uri to String.
            void onFragmentInteraction(String title);
        }

8. Repeat the same for other two fragments.

Hope this helped someone !

 

4 thoughts on “How to use navigation drawer activity in Android Studio

  1. There’s no need to change:
    —————import android.support.v4.app.Fragment;
    to:
    —————import android.app.Fragment;

    Because you can replace:

    Fragment fragment = new FragmentMain();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.mainFrame, fragment);
    ft.commit();

    to this:

    FragmentMain fragmentMain = new FragmentMain();
    getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame,fragmentMain).commit();

    Like

  2. I tried to connect navigation drawers & tabbed activity but its not working. Can you please explain me in detail. how to connect navigation drawers & tabbed activity

    Like

  3. I want to change drawer item icons, when i select different drawable file, app crashes.
    Default drawable are v21, and the one which i am adding, are v24. What should be the fix?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s