我可以通过xml在ActionBar
中添加子菜单项。
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代码添加这些子项?下面的代码不起作用,子项被添加到了错误的操作中(并且也没有显示可绘制对象),即最右侧的按钮而不是我的“New Form”按钮:
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代码添加子菜单项,而不使用PopupMenu
(http://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;
}