以编程方式将子菜单添加到菜单项-Android

以编程方式将子菜单添加到菜单项-Android,android,menu,submenu,Android,Menu,Submenu,我试图以编程方式向菜单项添加子菜单, 我该怎么做? 以下是我目前的代码: @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, R.id.extra_options, Menu.NONE, "Menu1") .setIcon(Config.chooseActionBarIcon( MainActivity.this, "ic_actionbar_

我试图以编程方式向菜单项添加子菜单, 我该怎么做? 以下是我目前的代码:

    @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”

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

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

<item
  android:id="@+id/menu_common_object"
  android:title="@string/menu_common_object">
  <menu></menu>
</item>
将在运行时正常工作。

您可以替换“menu.add”to be“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;
}

请注意,这可以简化:子菜单ThemeNu=menu.addSubMenu(menu.NONE,R.id.extra_选项,menu.NONE,“Menu1”);那个简化版对我有用。但是findItem()在回答中提供的示例中返回null。
@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;
}