我已经尝试过所有可能的解决方案.这是我的代码:
private Menu mMenu;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_article_detail_menu, menu);
mMenu = menu;
}
void changeStar(boolean added) {
if (mMenu != null) {
MenuItem item = mMenu.findItem(R.id.favourites_item);
if (added) {
Log.d(LOG_TAG, "Set full icon");
item.setIcon(getResources().getDrawable(R.drawable.star_full));
} else {
Log.d(LOG_TAG, "Set empty icon");
item.setIcon(getResources().getDrawable(R.drawable.star_empty));
}
}
}
这是我的菜单xml文件:
<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"
tools:context="ssidit.pp.ua.payspacereader.ArticleDetailActivity">
<item
android:id="@+id/refresh_item"
android:title="@string/refresh"
app:showAsAction="never"></item>
<item
android:id="@+id/favourites_item"
android:icon="@drawable/star_empty"
android:title="@string/add_to_favourite"
app:showAsAction="ifRoom"></item>
<item
android:id="@+id/share_item"
android:icon="@drawable/ic_share"
android:title="@string/share"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
app:showAsAction="ifRoom"></item>
</menu>
invalidateMenu()方法没有帮助.当我调用setIcon方法时,我的Android设备上没有任何变化.
这是我的代码:
private boolean isFavourite;
private void setValues(Cursor cursor) {
Log.d(LOG_TAG, "Setting values");
setData(titleTextView, CursorUtility.getTitle(cursor));
setData(dateTextView, CursorUtility.getDateText(cursor));
setData(timeTextView, CursorUtility.getTimeText(cursor));
isFavourite = CursorUtility.isFavourite(cursor);
getActivity().invalidateOptionsMenu();
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
Log.d(LOG_TAG, "OnPrepareOptionsMenu");
MenuItem item = menu.findItem(R.id.favourites_item);
if (isFavourite) {
Log.d(LOG_TAG, "Set full icon");
item.setIcon(R.drawable.star_full);
} else {
Log.d(LOG_TAG, "Set empty icon");
item.setIcon(R.drawable.star_empty);
}
}
如您所见,所有内容都已记录.因此,如果某些方法不调用则不会出错.我也通过获得它的标题来检查项目.这是正确的项目.只是某种黑魔法.
最佳答案 尝试使用invalidateOptionsMenu并将您的changeStar逻辑移动到onPrepareOptionsMenu.从
Android documentation开始:
public boolean onPrepareOptionsMenu (Menu menu)
Added in API level 1
Prepare the Screen’s standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.The default implementation updates the system menu items based on the activity’s state. Deriving classes should always call through to the base class implementation.