如何在 Android 中动态更改菜单项文本 [英] How to change menu item text dynamically in Android

查看:55
本文介绍了如何在 Android 中动态更改菜单项文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 onOptionsItemSelected(MenuItem item) 方法之外更改菜单项的标题.

I'm trying to change the title of a menu item from outside of the onOptionsItemSelected(MenuItem item) method.

我已经做了以下事情;

public boolean onOptionsItemSelected(MenuItem item) {
  try {
    switch(item.getItemId()) {
      case R.id.bedSwitch:
        if(item.getTitle().equals("Set to 'In bed'")) {
          item.setTitle("Set to 'Out of bed'");
          inBed = false;
        } else {
          item.setTitle("Set to 'In bed'");
          inBed = true;
        }
        break;
    }
  } catch(Exception e) {
    Log.i("Sleep Recorder", e.toString());
  }
  return true;
}

但是我希望能够在此方法之外修改特定菜单项的标题.

however I'd like to be able to modify the title of a particular menu item outside of this method.

推荐答案

正如 JxDarkAngel 建议的那样,从 Activity 的任何地方调用它,

As JxDarkAngel suggested, calling this from anywhere in your Activity,

invalidateOptionsMenu();

然后覆盖:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
  MenuItem item = menu.findItem(R.id.bedSwitch);
    if (item.getTitle().equals("Set to 'In bed'")) {
        item.setTitle("Set to 'Out of bed'");
        inBed = false;
    } else {
        item.setTitle("Set to 'In bed'");
        inBed = true;
    }
  return super.onPrepareOptionsMenu(menu);
}

是一个更好的选择.我使用了 https://stackoverflow.com/a/17496503/568197

is a much better choice. I used the answer from https://stackoverflow.com/a/17496503/568197

这篇关于如何在 Android 中动态更改菜单项文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆