Chloe
Chloe

Reputation: 26264

How do I change the text of my ContextMenu MenuItem?

How do I change the text of my pop up context menu items? I want the context menu to have a header, and I want to set it based on the underlying content. The context menu pops up find with static strings, but I want to change the titles dynamically. I can't seem to get a handle on the MenuItem objects!

Main.java:70: error: int cannot be dereferenced
[javac]             MenuItem mi = R.menu.context_menu.articleTitle;
                                                      ^

Here is the code to bring up the context menu:

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);
}

I also tried

    MenuItem mi = (MenuItem) findViewById(R.id.articleTitle);
    mi.setTitle(a.getTitle());

But it gave me a NullPointerException. Here is the menu resource:

<?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>

Upvotes: 0

Views: 3056

Answers (1)

nistv4n
nistv4n

Reputation: 2535

If you want to change the title of your context menu, use the setHeaderTitle() on your menu instance. To change the text (title) of a menuitem programatically, use the menu.findItem(R.id.menu_item_id_defined_in_your_XML). After that, you can change this MenuItem's attributes, like title, icon, showAsAction, etc.

@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");
}

Upvotes: 2

Related Questions