【问题标题】:Add Submenu to a Menuitem Programmatically - Android以编程方式将子菜单添加到菜单项 - Android
【发布时间】:2013-12-16 10:29:37
【问题描述】:

我正在尝试以编程方式将 SubMenu 添加到我的 MenuItem, 我怎么做? 到目前为止,这是我的代码:

    @Override
public boolean onCreateOptionsMenu(Menu menu) {

    menu.add(Menu.NONE, R.id.extra_options, Menu.NONE, "Menu1")
    .setIcon(Config.chooseActionBarIcon(
            MainActivity.this, "ic_actionbar_font"))
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

    SubMenu themeMenu = menu.findItem(R.id.extra_options).getSubMenu();
    themeMenu.clear();
    themeMenu.add(0, R.id.theme_auto, Menu.NONE, "Automatic");
    themeMenu.add(0, R.id.theme_day, Menu.NONE, "Default");
    themeMenu.add(0, R.id.theme_night, Menu.NONE, "Night");
    themeMenu.add(0, R.id.theme_batsave, Menu.NONE, "Battery Saving");


    return super.onCreateOptionsMenu(menu);
}

R.id.extra_options 是在“ids.xml”资源文件中定义的ID;

<item type="id" name="extra_options" />

使用 getSubMenu() 获取子菜单似乎没问题,但是当我尝试将项目添加到子菜单时,我收到错误“NullPointerException”

有人知道代码有什么问题吗?

【问题讨论】:

标签: android menu submenu


【解决方案1】:

您可以将“menu.add”替换为“menu.addSubMenu” 我想这会对你有所帮助

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.single_product, menu);

    menu.addSubMenu(Menu.NONE, R.id.extra_options, Menu.NONE,"Menu1");

     SubMenu themeMenu = menu.findItem(R.id.extra_options).getSubMenu();

     themeMenu.clear();
     themeMenu.add(0, R.id.theme_auto, Menu.NONE, "Automatic");
     themeMenu.add(0, R.id.theme_day, Menu.NONE, "Default");
     themeMenu.add(0, R.id.theme_night, Menu.NONE, "Night");
     themeMenu.add(0, R.id.theme_batsave, Menu.NONE, "Battery Saving");

    return true;
}

【讨论】:

  • 这可以简化:SubMenu themeMenu = menu.addSubMenu(Menu.NONE, R.id.extra_options, Menu.NONE,"Menu1");
  • 那个简化版对我有用。但是 findItem() 在答案中提供的示例中返回了 null。
【解决方案2】:

尝试将空的 menu 标签添加到您的菜单项中。像这样:

<item
  android:id="@+id/menu_common_object"
  android:title="@string/menu_common_object">
  <menu></menu>
</item>

之后

menuItem.getSubMenu().add(..)

在运行时可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-17
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多