我有一个这样的菜单资源文件:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
>
<group android:checkableBehavior="single">
<item android:id="@+id/sort_all"
android:title="All"
android:orderInCategory="1" />
<item android:id="@+id/sort_co"
android:title="CoAuthors"
android:orderInCategory="2" />
<item
android:id="@+id/sort_title"
android:title="Title"
android:orderInCategory="3" />
<item
android:id="@+id/sort_journal"
android:title="Journals"
android:orderInCategory="4" />
<item
android:id="@+id/sort_year"
android:title="Year"
android:orderInCategory="5" />
</group>
</menu>
我在弹出菜单上使用它:
final PopupMenu popup = new PopupMenu(MainActivity.this, btn1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.search_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.sort_co:
popup.getMenu().findItem(item.getItemId()).setChecked(true);
return true;
case R.id.sort_title:
item.setChecked(true);
return true;
case R.id.sort_journal:
item.setChecked(true);
return true;
case R.id.sort_year:
item.setChecked(true);
return true;
case R.id.sort_all:
item.setChecked(true);
return true;
default:
return true;
}
}
});
popup.show();
}
});
你可以看到我尝试过使用
item.setChecked(true)
和
popup.getMenu().findItem(item.getItemId()).setChecked(true);
但问题是当我在关闭菜单之前点击项目时,项目会被检查但是当我再次重新打开菜单时,它不会被检查! 我也尝试过使用
MenuItem subMenuItem = item.getSubMenu().getItem(INDEX_OF_ITEM);
subMenuItem.setChecked(!subMenuItem.isChecked());
但它给了我NullPointerException ...。
答案 0 :(得分:1)
您可以在代码中尝试进行此修改。像这样:
final PopupMenu popup = new PopupMenu(MainActivity.this, btn1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.search_menu, popup.getMenu());
int item_selected = 1;
if(item_selected == 1){
popup.getMenu().findItem(R.id.sort_co).setChecked(true);
}else if(item_selected == 2) {
popup.getMenu().findItem(R.id.sort_title).setChecked(true);
}
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.sort_co:
item.setChecked(true);
item_selected = 1;
return true;
case R.id.sort_title:
item.setChecked(true);
item_selected = 2;
return true;
default:
return true;
}
}
});
popup.show();