Adding an onclick to a submenu?

2019-03-27 09:48发布

问题:

I have an onclick function for my menu but I can't figure out what the ID is for my submenu so that I can tell the submenu what to do when the user click on it. I created my submenu programmatically using the code below. So if someone could please explain to me how I know what the id is for each item of the submenu I'd greatly appreciate it.

    @Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);

    SubMenu submenu = menu.addSubMenu(0, Menu.FIRST, Menu.NONE, "Preferences");
    submenu.add(0, Menu.FIRST, Menu.NONE, "Get Last 5 Packets");
    submenu.add(0, Menu.FIRST, Menu.NONE, "Get Last 10 Packets");
    submenu.add(0, Menu.FIRST, Menu.NONE, "Get Last 20 Packets");
    inflater.inflate(R.menu.mainmenu, submenu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle item selection
    switch (item.getItemId())
    {
        case R.id.viewKML:
            viewKML();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

回答1:

When you are adding

submenu.add(0, Menu.FIRST, Menu.NONE, "Get Last 5 Packets");

The parameter arrangement for add() method is Android Menu Add Method

public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title)

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

Is the id of your menu item. It should be unique. Like you say 15,20,21. This id will act like android:id="@+id/15". Is will be used when you are going to check which item is clicked

e.g

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_menu, menu);

        SubMenu submenu = menu.addSubMenu(0, Menu.FIRST, Menu.NONE, "Preferences");
        submenu.add(0, 10, Menu.NONE, "Get Last 5 Packets");
        submenu.add(0, 15, Menu.NONE, "Get Last 10 Packets");
        submenu.add(0, 20, Menu.NONE, "Get Last 20 Packets");
        inflater.inflate(R.menu.main_activity_menu, submenu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case 10:
            Toast.makeText(LoginPageActivity.this, "Now "+item.getItemId(), Toast.LENGTH_SHORT).show();
            return true;
        case 15:
            Toast.makeText(LoginPageActivity.this, "Now = "+item.getItemId(), Toast.LENGTH_SHORT).show();
            return true;
        case 20:
            Toast.makeText(LoginPageActivity.this, "Now == "+item.getItemId(), Toast.LENGTH_SHORT).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }