我在 ActionBar 子菜单中有一些项目,我想有条件地禁用它们,因为它们不适用于某些上下文。我希望它们显示为禁用(灰色)以阻止用户点击它们;但是如果单击,我想显示一个 toast 通知用户为什么它被禁用(“不能做 A,因为没有 B”等)。但是,如果我调用 MenuItem.setEnabled(false),似乎所有菜单项单击事件都不会发生。那么,如何检测对禁用菜单项的单击?
public class Temp extends Activity implements OnMenuItemClickListener
{
boolean mConditional = true;
protected void onCreate(Bundle state)
{
super.onCreate(state);
}
public boolean onMenuOpened(int featureId, Menu menu)
{
MenuItem item = (MenuItem) menu.findItem(R.id.item2);
if(item != null && mConditional)
{
item.setEnabled(false);
item.setOnMenuItemClickListener(this);
}
return super.onMenuOpened(featureId, menu);
}
@Override
public boolean onMenuItemClick(MenuItem item)
{
//does not fire if item is disabled
Log.e("", item.getTitle().toString());
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
//does not fire if item is disabled
Log.e("", item.getTitle().toString());
return super.onOptionsItemSelected(item);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
//does not fire if item is disabled
Log.e("", item.getTitle().toString());
return super.onMenuItemSelected(featureId, item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
}
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu"
android:icon="@drawable/ic_launcher"
android:showAsAction="always"
android:title="menu">
<menu>
<item
android:id="@+id/item1"
android:showAsAction="always"
android:title="item 1"/>
<item
android:id="@+id/item2"
android:showAsAction="always"
android:title="item 2"/>
<item
android:id="@+id/item3"
android:showAsAction="always"
android:title="item 3"/>
</menu>
</item>
</menu>