用同一菜单中的另一个菜单项位置替换菜单项位置

时间:2017-04-06 06:47:52

标签: android menu

我正在尝试为卡片视图创建一个上下文菜单。初始菜单就像 图1:初始上下文菜单

enter image description here

我需要替换它,如图2:替换上下文菜单

enter image description here

。当我点击禁用菜单时,卡片视图将被禁用,禁用菜单应替换为启用菜单

2 个答案:

答案 0 :(得分:1)

单击菜单项以更改菜单项标题后调用invalidateOptionsMenu()。

Boolean IsEnable = false;

@Override
public boolean onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuItem reminderstatus = (MenuItem) menu.findItem(R.id.reminderstatus);
    if (IsEnable) {
        reminderstatus.setTitle("Disable");
    } else {
        reminderstatus.setTitle("Enable");
    }
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    return super.onContextItemSelected(item);
    if (item.getItemId() == R.id.reminderstatus) {
        if (IsEnable) {
            IsEnable = false;
        } else {
            IsEnable = true;
        }
        invalidateOptionsMenu();
    }
}

答案 1 :(得分:0)

实际上,您不需要为启用和禁用创建不同的菜单项,只需单个菜单项,只需更改其状态(启用或禁用)菜单项的文本。 希望您保存当前启用或禁用的状态。

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);

    // Select a menu item then change it's title (text)
    MenuItem mi = (MenuItem) menu.findItem(R.id.YOUR_MENU_ID);
    if(CHECK_YOUE_CURRENT_STATUS_HERE){

      //SET YOUR CURRENT STATUS ACCORDINGLY CURRENT STATUS (ENABLE /DISABLE)
      mi.setTitle("Enable/Disable");

    }
}
@Override
public boolean onContextItemSelected(MenuItem item) {
    return super.onContextItemSelected(item);
    if (item.getItemId() == R.id.reminderstatus) {
        if (YOUR_CURRENT_STATUS) {
            YOUR_CURRENT_STATUS = false;
        } else {
            YOUR_CURRENT_STATUS = true;
        }
        invalidateOptionsMenu();
    //this method refresh your Context menu view so basically call 
    // your onCreateContextMenu once again which will check for your 
    // Status and set accordingly it.
        }
    }

只需检查此示例代码实现它正确适用于您。