Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a tag to MenuItem?

I am building a popup menu in android and I need to store some IDs in each menu item. The IDs are String therefore it would be nice if I could set an array of String to the MenuItem.

The problem is that MenuItem does not have setTag method.

How else can I attach some data to it?

EDIT: Geobits mentioned about getActionView();

Unfortunately it returns null.

However, is it save to do the following?

 View view = new View(getActivity());
 view.setTag(tag);
 menuItem.setActionView(view);
like image 698
Arturs Vancans Avatar asked Mar 10 '13 19:03

Arturs Vancans


1 Answers

Each MenuItem has an associated View called an ActionView. If you're using a custom ActionView, you can fetch it using MenuItem.getActionView(), and set/retrieve the tag on it.

For instance, to set a tag:

public void setMenuItemTag(MenuItem item, Object tag)
{
    View actionView = item.getActionView();
    actionView.setTag(tag);
}

Edit

If you're not using a custom ActionView, you can use a HashMap to store tags. Use the MenuItem as the key.

public void setMenuItemTag(MenuItem item, Object tag)
{
    myMap.put(item, tag);
}

// returns null if tag has not been set(or was set to null)
public Object getMenuItemTag(MenuItem item, Object tag)
{
    return myMap.get(item);
}
like image 150
Geobits Avatar answered Sep 24 '22 20:09

Geobits