1
我正在使用城市的ArrayList
填充子菜單。我似乎無法弄清楚如何獲得在子菜單中點擊的MenuItem
的ID。我找不到適合我需求的方法。Android - 獲取子菜單中點擊的MenuItem的項目標識
讓我與你分享我的代碼。任何幫助將不勝感激。
@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;
}