如何更改弹出上下文菜单项的文本?我希望上下文菜单有一个标题,我想根据底层内容进行设置。上下文菜单弹出查找静态字符串,但我想动态更改标题。我似乎无法掌握MenuItem对象!
Main.java:70: error: int cannot be dereferenced
[javac] MenuItem mi = R.menu.context_menu.articleTitle;
^
以下是调出上下文菜单的代码:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
Article a = display.getArticle();
MenuItem mi = R.menu.context_menu.articleTitle;
mi.setTitle(a.getTitle());
mi = R.id.articleURL; // this doesn't work either
mi.setTitle(a.url);
}
我也试过
MenuItem mi = (MenuItem) findViewById(R.id.articleTitle);
mi.setTitle(a.getTitle());
但它给了我一个NullPointerException。这是菜单资源:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="@+id/contextHeader"
android:enabled="false"
>
<item android:id="@+id/articleTitle"
android:title="Title"
/>
<item android:id="@+id/articleURL"
android:title="URL"
/>
</group>
<item android:id="@+id/share"
android:title="Share"
android:icon="@android:drawable/ic_menu_share"
/>
<item android:id="@+id/skip"
android:title="Skip"
android:icon="@android:drawable/ic_media_next"
/>
</menu>
答案 0 :(得分:0)
如果要更改上下文菜单的标题,请使用菜单实例上的setHeaderTitle()。 要以编程方式更改menuitem的文本(标题),请使用menu.findItem(R.id.menu_item_id_defined_in_your_XML)。之后,您可以更改此MenuItem的属性,例如title,icon,showAsAction等。
@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);
//Set a title for the context menu
menu.setHeaderTitle("Title of menu");
// Select a menu item then change it's title (text)
MenuItem mi = (MenuItem) menu.findItem(R.id.new_game);
mi.setTitle("Text of item");
}