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" f开发者_运维问答or 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!
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 TextView
s 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.
The way I would do this is to create two separate menu items, "Mark as read" and "Mark as unread" and then hide one of them whenever the menu is displayed:
@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);
if (<is unread>)
menu.findItem(R.id.mark_unread).setVisible(false);
else
menu.findItem(R.id.mark_read).setVisible(false);
}
Setting the text (and especially reading the text) directly from code is brittle; the text may change, and what if you want to support multiple languages?
精彩评论