我在XML中定义了一个 PopupMenu ,它是片段
的一部分<menu xmlns:com.itrash.android="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="@+id/order_by_menu" android:checkableBehavior="single">
<item android:id="@+id/action_show_discounts_only"
android:title="@string/discounts_only_title" />
<item android:id="@+id/action_show_all"
android:title="@string/all_title" />
</group>
菜单链接到 ImageButton (来自 onActionCreated()的摘录)
final SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
this.onlyDiscounts = prefs.getBoolean(PROPERTY_ONLY_DISCOUNTS, false);
this.orderBy = prefs.getString(PROPERTY_ORDER_BY, ORDER_BY_NAME);
this.filterButton = (ImageButton) getActivity().findViewById(R.id.filter_button);
this.filterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
filterMenu.show();
}
});
this.filterMenu = new PopupMenu(getActivity(), getActivity().findViewById(R.id.filter_button));
this.filterMenu.inflate(R.menu.product_filter_menu);
this.filterMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
onFilterClick(item);
return true;
}
});
单击时,将调用以下方法
private void onFilterClick(MenuItem item) {
boolean showDiscountsOnly = item.getItemId() == R.id.action_show_discounts_only ? true : false;
item.setChecked(!item.isChecked());
if (this.onlyDiscounts != showDiscountsOnly) {
this.onlyDiscounts = showDiscountsOnly;
productSearchResultAdapter.clear();
this.curPage = 1;
doSearchProducts();
}
final SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(PROPERTY_ONLY_DISCOUNTS, showDiscountsOnly);
editor.commit();
}
我遇到的问题是从 SharedPreferences 检索时,如何根据属性 onlyDiscounts 恢复菜单项的状态? 换句话说,如果 onlyDiscounts 为真,我想要检查菜单项* action_show_discounts_only *。
我试图在 onActionCreated()内放置一些内容
for (int i = 0; i < this.filterMenu.getMenu().size(); i++) {
MenuItem item = this.filterMenu.getMenu().getItem(i);
if (item.getItemId() == R.id.action_show_discounts_only) {
item.setChecked(true);
} else {
item.setChecked(false);
}
}
甚至
this.filterMenu.getMenu().findItem(R.id.action_show_discounts_only).setChecked(this.onlyDiscounts);
this.filterMenu.getMenu()则findItem(R.id.action_show_all).setChecked(this.onlyDiscounts!);
两次尝试都被忽略,* R.id.action_show_all *项始终检查,无论 onlyDiscounts 是什么值。
知道如何解决这个问题吗?