Android:如何根据三点菜单选项修改菜单栏指定项的显示文本
解决方案
这问题其实很容易解决,核心就是在选中菜单选项后,直接更新目标MenuItem的标题就行。我帮你调整下代码,一步步来:
第一步:定义成员变量保存目标MenuItem
首先在你的Activity类里添加一个成员变量,用来保存需要修改标题的那个MenuItem,这样后续不用每次都重新查找:
private MenuItem mTitleMenuItem;
第二步:初始化并设置初始标题
在onCreateOptionsMenu方法里,把目标MenuItem赋值给这个成员变量,同时设置初始的"SingleCell"标题:
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); // 这里建议用findItem通过id查找,比getItem(0)更可靠(避免菜单顺序变化导致出错) // 替换成你实际的标题项id,比如R.id.action_title_item mTitleMenuItem = menu.findItem(R.id.action_title_item); // 如果确定索引是0,也可以用menu.getItem(0),但findItem更稳妥 // mTitleMenuItem = menu.getItem(0); mTitleMenuItem.setTitle("SingleCell"); return true; }
提示:尽量用
findItem通过控件ID查找目标MenuItem,而不是依赖索引getItem(0),因为如果后续菜单布局调整顺序,索引会失效,用ID更稳定。
第三步:在菜单选中事件里更新标题
修改onOptionsItemSelected方法,在每个选项的分支里,调用setTitle更新标题:
@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.navigation_multicell) { selectState = 0; boxState = 0; // 更新标题为Multicell mTitleMenuItem.setTitle("Multicell"); return true; } if (id == R.id.navigation_singlecell) { selectState = 1; boxState = 0; // 更新标题为SingleCell mTitleMenuItem.setTitle("SingleCell"); return true; } if (id == R.id.navigation_box) { selectState = 2; boxState = 0; // 更新标题为Box(你可以根据实际需求修改这个文本) mTitleMenuItem.setTitle("Box"); return true; } return super.onOptionsItemSelected(item); }
这样当你点击三点菜单里的任意选项时,ActionBar上的目标文本就会跟着切换成对应的内容了。
内容的提问来源于stack exchange,提问作者Kucing Kiki
相关产品推荐
相关产品推荐

