android – 在子菜单中添加onclick?

前端之家收集整理的这篇文章主要介绍了android – 在子菜单中添加onclick?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的菜单有一个onclick功能,但我无法弄清楚我的子菜单的ID是什么,以便我可以告诉子菜单用户点击它时该做什么.我使用下面的代码以编程方式创建了子菜单.所以,如果有人能够向我解释我如何知道子菜单的每个项目的id是什么我会非常感激.
@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,"Get Last 5 Packets");
    submenu.add(0,"Get Last 10 Packets");
    submenu.add(0,"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);
    }
}

解决方法

当你添加
submenu.add(0,"Get Last 5 Packets");

add()方法的参数排列是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.

菜单项的ID.它应该是独一无二的.就像你说15,20,21.这个id就像android:id =“@ id / 15”.当您要检查单击哪个项目时将使用

例如

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

        SubMenu submenu = menu.addSubMenu(0,"Preferences");
        submenu.add(0,10,"Get Last 5 Packets");
        submenu.add(0,15,"Get Last 10 Packets");
        submenu.add(0,"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);
        }
    }

猜你在找的Android相关文章