private static final int MY_MENU_1 = Menu.FIRST;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MY_MENU_1, 0, "Hello").setShortcut('3', 'c');
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MY_MENU_1:
return true;
}
return super.onOptionsItemSelected(item);
}
我需要使用这些optionmenuitem
点击来添加或删除我的button
答案 0 :(得分:1)
仅根据您的情况更改视图的可见性:
btn.setOnClickListener(v->{
if(condition)
menu.findItem(R.id.id_name).setVisible(true);
else
menu.findItem(R.id.id_name).setVisible(false);
});
答案 1 :(得分:0)
这样,您可以在运行时添加或删除它们。
PopupMenu popupMenu = new PopupMenu(YourActivity.this, view);
popupMenu.getMenu().add(1, R.id.complain_the_user, 3, R.string.complain_the_user);
popupMenu.getMenu().add(2, R.id.mute, 3, R.string.mute);
popupMenu.show();
菜单-> popup_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/block"
android:title="@string/block"/>
<item android:id="@+id/mute"
android:title="@string/mute"/>
<item android:id="@+id/complain_the_user"
android:title="@string/complain_the_user"/>
</menu>
答案 2 :(得分:0)
您可以在onCreateOptionsMenu()中创建按钮时添加布尔变量:
private static Boolean condition = true;
@Override public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
if (condition) {
menu.add(0, MY_MENU_1, 0, "Hello").setShortcut('3', 'c');
}
return true;
}
然后,当单击项目时,您应该在onOptionsItemSelected()中更改变量并调用invalidateOptionsMenu()以便重建菜单列表:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case MY_MENU_1:
condition = false;
invalidateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
答案 3 :(得分:0)
您可以在onCreateOptionsMenu中增加菜单,并可以在onPrepareOptionsMenu中执行添加和删除(可见或不可见)的操作。
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.MY_MENU_1, menu);
return true;
}
//choose visibility for menu item using displayItem= true/false
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem menuItem = menu.findItem(R.id.MY_MENU_1);
if(displayItem)
menuItem.setVisible(true);
else
menuItem.setVisible(false);
return super.onPrepareOptionsMenu(menu);
}