Home > Software engineering >  How can I fix the problem that a MenuItem takes on the ID of a previous one
How can I fix the problem that a MenuItem takes on the ID of a previous one

Time:01-04

At the beginning I have two items and the 2nd gets a listener with:

final View view = findViewById(R.id.list_item);
                if (view != null) {
                    view.setOnLongClickListener(v -> {
                        Toast.makeText(getApplicationContext(), "Long pressed", Toast.LENGTH_SHORT).show();
                        return true;
                    });
                }
            }

But if I add a new item with menu.add("name"); the listener is on the newly added item and not on the old one (list_item)

I have already tested many other alternatives, but they don't work! I just need help on how to keep the item ID or how the listener stays on the item.

CodePudding user response:

When you add an item using ``menu.add(...)` it returns a reference to the newly added item. You can set the listener like this:

    final MenuItem newItem = menu.add("New item");
    newItem.setOnMenuItemClickListener(menuItem -> {
        // Handle your click here!
        return true;
    });

However, you should add/remove menu items by overriding onPrepareOptionsMenu(Menu menu). When you use menu.add(...) use the overload that allows you to set the itemId:

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, 314159, Menu.NONE, "New item");
        
        return super.onPrepareOptionsMenu(menu);
    }

Note that the above will be called each time the menu is going to be shown (very convenient).

Then you can handle the menu being selected from onOptionsItemSelected:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 314159) {
            // Handle menu selection here!
        }
        return super.onOptionsItemSelected(item);
    }

Check the AppBar/Menu guide here: https://developer.android.com/training/appbar

  •  Tags:  
  • Related