millinet millinet - 4 months ago 20
Android Question

Android - get item id of an MenuItem clicked in a Submenu

I'm populating a submenu with an

ArrayList
of cities. I can't see to figure out how to get the id of
MenuItem
clicked in the submenu. I couldn't find a method that might suit my needs.

Let me share my code with you. Any help would be highly appreciated.

@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);
}


The method that add cities to the submenu

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++;
}
}


The onNavigationItemSelected method in which I get the id of the clicked submenu

@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;
}

Answer

You'll have to set an id on the menu items. Setting an id is only possible with one of the add methods of Menu, e.g. with Menu.add(). Change your addCitiestoMenu():

private void addCitiestoMenu() {

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

    for (City city : cityArrayList) {
        int cityId = city.getId(); // Get the id (You'll probably need to replace getId() )
        MenuItem item = submenu.add(Menu.NONE, cityId, Menu.NONE, city.getCityName());
        item.setIcon(R.drawable.ic_place_black_24dp);
    }
}
Comments