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" />
Which method is used to handle click on the menu items of the navigation view? You have to use OnNavigationItemSelectedListener(MenuItem item) method.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With