tags:

views:

42

answers:

1

Is it possible to create a dynamic context menu in android?

What I mean is, for example, if I have a list of items, that can be in two states: "read" and "unread". I want to be able to bring up a context menu with an option of "Mark as Read" for the unread items, and "Mark as Unread" for the read items.

So clicking on:

> read
> unread <-- click
> read 

will show context menu "Mark as Read" resulting in:

> read
> read
> read   <-- click

will show the menu "Mark as Unread".

Is there some function that allows me to customize the creation of the context menu, just before it is displayed?

Any help is welcome!

+2  A: 

As you don't provide code, this is is the basic approach:

@Override
public void onCreateContextMenu(ContextMenu contextMenu,
                                View v,
                                ContextMenu.ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info =
            (AdapterView.AdapterContextMenuInfo) menuInfo;

    String actionString = "Mark as Read";

    // if it's alredy read
    if ( ((TextView) info.targetView).getText().toString().equals("read") )
        actionString = "Mark as Unread";

    menu.setHeaderTitle("Action");
    menu.add(0, 0, 0, actionString);
}

In this case, I'm assuming the list is populated with TextViews that can have the string "read" or "unread" in it. As I already said, this is a very basic approach. The important thing here is to notice how the ContextMenu.ContextMenuInfo object is being used.

Also, to read the state of the item that was selected you can use the item.getMenuInfo() method inside the onContextItemSelected(MenuItem item) method.

Cristian
What does the .targetView member represent? Thank you!
drozzy
When you build a List on Android, each item in the list is a `View`. You can use different types of Views, for instance a simple `TextView` (as in the example above) or a custom view (for example, an external layout into an XML with a `LinearLayout`, different `TextView`s, Images, etc). The `targetView` represents the `View` your are using to display each item in the list.
Cristian