How to add click event to item on NavigationView of Android

Sushil Shinde picture Sushil Shinde · Feb 28, 2017 · Viewed 17.5k times · Source

I am trying to implement Sidebar NavigationDrawer in my Android project. To do so, I have used NavigationView in DrawerLayout. To show items I used menu. I want to add click event on that added menu items.

Code for reference: In navigation menu -

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/nav_account" android:title="My Account"/>
    <item android:id="@+id/nav_settings" android:title="Settings"/>
    <item android:id="@+id/nav_layout" android:title="Log Out"/>
</menu>

In View:

<android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/navigation_menu"
        android:layout_gravity="start" />

Answer

Nizam picture Nizam · Feb 28, 2017
  1. Implement the listener in your Activity:

    public class HomeActivity extends AppCompatActivity implements 
                  NavigationView.OnNavigationItemSelectedListener
    
  2. setNavigationItemSelectedListener in onCreate of Activity

    NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);
    
    if (mNavigationView != null) {
            mNavigationView.setNavigationItemSelectedListener(this);
    }
    
  3. Override the method

    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
    
        if (id == R.id.nav_account) {
           // DO your stuff 
        }
    }