Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add click event to item on NavigationView of Android

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" />
like image 569
Sushil Shinde Avatar asked Feb 28 '17 03:02

Sushil Shinde


People also ask

Which method is used to handle clicks on the menu items of the navigation view?

Which method is used to handle click on the menu items of the navigation view? You have to use OnNavigationItemSelectedListener(MenuItem item) method.

Can we use activity in navigation drawer?

As for how to switch between activities via the navigation drawer, you can just set up new intents within your selectItem() method: private void selectItem(int position) { // Handle Navigation Options Intent intent; switch (position) { case 0: intent = new Intent(currentActivity, NewActivity. class); intent.


1 Answers

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!

like image 136
SamPhoenix Avatar answered Nov 16 '22 00:11

SamPhoenix