Android - 获取在子菜单中单击的MenuItem的项目ID

时间:2016-07-24 11:02:47

标签: android navigation

我填充了ArrayList个城市的子菜单。我似乎无法弄清楚如何在子菜单中点击MenuItem的ID。我无法找到适合我需要的方法。

让我与您分享我的代码。任何帮助都将受到高度赞赏。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_base);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    mToolbar.setTitleTextAppearance(this, R.style.TextAppearance_Widget_Event_Toolbar_Title);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(
            this, mDrawerLayout, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerToggle.syncState();

    mFrameLayout = (FrameLayout) findViewById(R.id.content_frame);

    NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
    mDrawerMenu = navigationView.getMenu();

    addCitiestoMenu();

    navigationView.setNavigationItemSelectedListener(this);
}

将城市添加到子菜单的方法

private void addCitiestoMenu() {

    cityArrayList = RealmHelper.getStoredCities();
    SubMenu submenu = mDrawerMenu.getItem(0).getSubMenu();
    submenu.setIcon(R.drawable.ic_place_black_24dp);
    submenu.setHeaderTitle("test");

    int i = 0;

    for (City city: cityArrayList) {
        submenu.add(city.getCityName());
        submenu.getItem(i).setIcon(R.drawable.ic_place_black_24dp);
        i++;
    }
}

onNavigationItemSelected方法,我在其中获取所点击子菜单的ID

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Log.v(LOG_TAG, "id: "+id);

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

1 个答案:

答案 0 :(得分:0)

您必须在菜单项上设置ID。只能使用add的{​​{1}}方法之一设置ID,例如与Menu.add()。更改您的Menu

addCitiestoMenu()