如何在代码中向ActionBar操作添加子菜单项?

时间:2012-02-18 18:56:51

标签: android android-3.0-honeycomb menuitem android-actionbar

通过xml我可以在ActionBar

中为我的操作添加子菜单项

enter image description here

main_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_new_form"
          android:icon="@drawable/ic_new_form"
          android:title="@string/menu_new_form"
          android:showAsAction="ifRoom|withText">
        <menu>
            <item android:id="@+id/form1"
                  android:icon="@drawable/attachment"
                  android:title="Form 1"
                  android:onClick="onSort" />
            <item android:id="@+id/form2"
                  android:icon="@drawable/attachment"
                  android:title="Form 2"
                  android:onClick="onSort" />
        </menu>
    </item>
</menu>

但是如何通过Java代码添加这些子项?它不能工作如下,子项被添加到错误的操作(也没有显示drawable),非常正确的按钮,而不是我的'新表单'按钮:

enter image description here

main_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_new_form"
          android:icon="@drawable/ic_new_form"
          android:title="@string/menu_new_form"
          android:showAsAction="ifRoom|withText">
    </item>
</menu>

Java代码:

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

    Log.d("MainMenu", ",menu title0: " + menu.getItem(0).getTitle()); 
    // returns "New Form"

    menu.addSubMenu(0, Menu.NONE, 1, "Form 1").setIcon(R.drawable.attachment);
    menu.addSubMenu(0, Menu.NONE, 2, "Form 2").setIcon(R.drawable.attachment);
    return true;
}

有没有办法实现这一点,通过Java代码而不是XML添加子菜单项,没有使用PopupMenuhttp://developer.android.com/guide/topics/ui/menus.html#PopupMenu)?

更新(解决方案):

我最后的代码片段最后是根据adamp的回复动态填充子菜单:

// menu options
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final int MENU_LOGOUT = 2;

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    super.onCreateOptionsMenu(menu);

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    menu.add(0, MENU_PREFERENCES, 0, getString(R.string.general_preferences)).setIcon(
            android.R.drawable.ic_menu_preferences);

    // load all available form templates
    Cursor c = managedQuery(FormsProviderAPI.FormsColumns.CONTENT_URI, null, null, null, null);
    try {
        int ixDisplayName = c.getColumnIndex(FormsProviderAPI.FormsColumns.DISPLAY_NAME);
        int ixId = c.getColumnIndex(FormsProviderAPI.FormsColumns._ID);
        int cnt = 0;
        while (c.moveToNext()) {
            cnt++;
            Log.d("ID: ", "ID: "+ c.getInt(ixId));  // misusing the group id for the form id
            menu.getItem(1).getSubMenu().addSubMenu(c.getInt(ixId), Menu.NONE, cnt, c.getString(ixDisplayName)).setIcon(R.drawable.attachment_dark);
        }
    } catch (Exception e) {
        Log.e(TAG, "Error init form templates list.", e);
    }

    return true;
}

3 个答案:

答案 0 :(得分:35)

是的,有。

addSubMenu方法返回SubMenu个对象。 SubMenu也是Menu,因此您可以在其上调用add将项目添加到子菜单而不是父菜单。您上面的代码为表单1和表单2创建了两个不同的子菜单,而不是在单个“新建表单”子菜单中创建了两个项目。

示例:

SubMenu submenu = menu.addSubMenu(0, Menu.NONE, 1, "New Form").setIcon(R.drawable.ic_new_form);
submenu.add("Form 1").setIcon(R.drawable.attachment);

答案 1 :(得分:2)

添加ActionProvider可能更容易。您可以按照here

的说明进行尝试

答案 2 :(得分:1)

您应该考虑使用ActionProvider

示例:https://gist.github.com/sibelius/7ca0b757492ff6740dec

带有操作提供商项目的菜单

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <item android:id="@+id/action_companies"
        android:icon="@drawable/ic_list"
        android:title="@string/action_companies"
        app:actionProviderClass="com.example.MyActionProvider"
        app:showAsAction="always"/>
</menu>

代码

public class MyActionProvider extends ActionProvider {

    private Context mContext;

    public MyActionProvider(Context context) {
        super(context);

        mContext = context;
    }

    @Override
    public View onCreateActionView() {
        //LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        return null;
    }

    @Override
    public void onPrepareSubMenu(SubMenu subMenu) {
        super.onPrepareSubMenu(subMenu);

        subMenu.clear();

        subMenu.add("menu 1");
        subMenu.add("menu 2");
        subMenu.add("menu 3");
    }

    @Override
    public boolean hasSubMenu() {
        return true;
    }

    @Override
    public boolean onPerformDefaultAction() {
        return super.onPerformDefaultAction();
    }
}