用于 API < 11的 Android 无效选项菜单()

我使用了 ActivityCompat.invalidateOptionsMenu(MainActivity.this);,这样我的菜单项“刷新”可以自动启用/禁用,而无需使用必须触摸“菜单”选项(想象用户让菜单打开... 我需要“刷新”菜单项自动禁用并启用自己)。

ActivityCompat.invalidateOptionsMenu(MainActivity.this)在 Android 11 + 中运行良好。但是我可以为 android API < 11使用什么呢?S 我找了这么多,但是找不到答案。有人能帮帮我吗?

这在使用 onPrepareOptionsMenuActivityCompat.invalidateOptionsMenu(MainActivity.this)的 Android API 11 + 中可以很好地工作。 问题在于如何在 Android API < 11中完成。

下面是我的 onPrepareOptionsMenu方法:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(menuRefreshEnable){
menu.getItem(0).setEnabled(true);
}
if(!menuRefreshEnable){
menu.getItem(0).setEnabled(false);
}
return true;
}
20517 次浏览

This will return true if the API is above or equal to 11 and therefore supported. Before API 11, the menu is drawn when the menu button is pressed so there is no need for this method as it occurs automatically.

On API < 11 use supportInvalidateOptionsMenu() method

ActivityCompat.invalidateOptionsMenu() doesn't callback onPrepareOptionsMenu(); it just update the menu directly. Just put some Log.d() and check out by yourself.

This works for me (I'm using API 8):

private Menu mMenu;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.track_fragment, menu);
mMenu = menu;
}
...
private void someMethod() {
...
if (mMenu != null) {
MenuItem item = mMenu.findItem(R.id.new_track);
if (item != null) {
item.setVisible(false);
ActivityCompat.invalidateOptionsMenu(this.getActivity());
}
}
...
}

My someMethod() get called from several places, even before onCreateOptionsMenu(), so I must check mMenu != null.