How to add click event to item on NavigationView of Android

℡╲_俬逩灬. 提交于 2019-12-01 04:18:45

问题


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" />

回答1:


  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 }
        ...
    }
    



回答2:


You have to use OnNavigationItemSelectedListener(MenuItem item) method.

for more check this documentation.




回答3:


Here is a Java 8 approach with smaller boilerplate (no "implements" on Activity). Also helpful if your class is abstract and you don't want to implement this functionality in every other child:

@Override
protected void onCreate(
  Bundle savedInstanceState) {

  NavigationView navigationView =
    findViewById(
      R.id.navigationView);

  navigationView.setNavigationItemSelectedListener(
    MyActivity::onNavigationItemSelected);
}

public static boolean onNavigationItemSelected(MenuItem item) {

  if (item.getId() == R.id.my_item) {
    myItemClickHandler();
  }

  return false;
}


来源:https://stackoverflow.com/questions/42499696/how-to-add-click-event-to-item-on-navigationview-of-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!