Android : Get view Reference to a Menu Item Android : Get view Reference to a Menu Item android android

Android : Get view Reference to a Menu Item


You can achieve this by providing your menu item with an actionViewClass property in xml and then you will be able to get the pivot view u wanted. The code would be something like this

<item    android:id="@+id/menu_find"    android:showAsAction="ifRoom"    android:actionViewClass="android.widget.ImageButton"    />

In your OnCreateOptionsMenu do this

public boolean onCreateOptionsMenu(Menu menu) {    super.onCreateOptionsMenu(menu);    getMenuInflater().inflate(R.menu.menu_search, menu);    locButton = (ImageButton) menu.findItem(R.id.menu_find).getActionView();    locButton.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View v) {            // TODO Auto-generated method stub            createPopup();            mQuickAction.show(v);        }    });    return true;}


Old question, but I ran into some issues with the actionViewClass attribute. For anyone who runs into this later...

Calling findViewById(R.id.mnu_item) in onOptionsItemSelected will return a View anchor.

QuickActions on the MenuItems aren't good design, but I found that they are the simplest way to implement submenus with custom backgrounds.


Inorder to get reference Views of menu items we need to do this,

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.section, menu);    new Handler().post(new Runnable() {        @Override        public void run() {            final View menuItemView = findViewById(R.id.action_preview);            // SOME OF YOUR TASK AFTER GETTING VIEW REFERENCE        }    });    return true;}