How to add click event to item on NavigationView of Android
You have to use OnNavigationItemSelectedListener(MenuItem item)
method.
for more check this documentation.
I wanted to make sure the Solution from Nizam can be found in Kotlin to, since it is takeing bigger place every day:
val mDrawerLayout = this.findViewById(R.id.drawer_layout) as DrawerLayout
val mNavigationView = findViewById<View>(R.id.navigation) as NavigationView
Handle the navigation items in onCreate like this:
mNavigationView.setNavigationItemSelectedListener { it: MenuItem ->
when (it.itemId) {
R.id.nav_item1 -> doThis()
R.id.nav_item2-> doThat()
else -> {
true
}
}
}
Remember: Return Type has to be a boolean!
Implement the listener in your Activity:
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
setNavigationItemSelectedListener in onCreate of Activity
NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view); if (mNavigationView != null) { mNavigationView.setNavigationItemSelectedListener(this); }
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 } }