android - 将数据设置为 NavigationView 菜单项

标签 android android-menu navigation-drawer android-navigationview

如果我将自定义项目添加到我的 NavigationView 菜单中,如下所示:

Menu menu = navigationView.getMenu();

MenuItem item = menu.add("Item 1");

如何为项目(如对象)设置数据,以便在单击/选择它时,可以将该数据传递到它打开的 Activity ?

最佳答案

您无法向菜单项设置/添加数据。通过查看documentation add()方法中,可以看到可以设置:

groupId - int: The group identifier that this item should be part of. This can be used to define groups of items for batch state changes. Normally use NONE if an item should not be in a group.

itemId - int: Unique item ID. Use NONE if you do not need a unique ID.

order - int: The order for the item. Use NONE if you do not care about the order. See getOrder().

title - CharSequence: The text to display for the item.

因此:

您需要设置itemId并在onNavigationItemSelected()内处理特定任务

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.

    int id = item.getItemId();

    if (id == R.id.id_of_menu_item_1) {

        // handle intents and passing data

    } else if (id == R.id.id_of_menu_item_2) {

        // handle intents and passing data

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

关于android - 将数据设置为 NavigationView 菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42233700/

相关文章:

java.net.协议(protocol)异常 : Too many redirects in Android

android - 为什么我的进程在应用程序崩溃后仍然存在?

安卓滑出菜单

android - onOptionsItemSelected() 在 Fragment 上被调用两次

android - 自定义View onDraw不断被调用

android - 隐藏操作栏,显示选项菜单

cordova - ionic / Cordova 菜单按钮事件未调用

android - 如何在菜单项之后的抽屉导航中显示 TextView ?

javascript - React Native - 如何使用 StackNavigator 和 DrawerNavigator 管理每页的标题

android drawerlayout with actionbarsherlock