Get the view from the action bar menu item

Every where call:

activity.findViewById(R.id.menu_item);

If your code inside fragment don't use:

getView().findViewById(R.id.menu_item); 

It will return null.


findViewById doesn't have to be run on onOptionsItemSelected in order to get the view of the action item.

however, do note that sometimes action items get to be inside the overflow menu so you might get a null instead.

so, how can you do it?

here's a sample code:

public boolean onCreateOptionsMenu(final Menu menu) {
  getSupportMenuInflater().inflate(R.menu.main, menu);
  new Handler().post(new Runnable() {
    @Override
    public void run() {
      final View menuItemView = findViewById(R.id.menu_action_item);
      ...

this was tested when using actionBarSherlock library, on android 4.1.2 and android 2.3.5 .

another alternative is to use a more extensive way , used on the showcaseView library, here .


I meet this issue as well, findViewById should be worked by my side, here is the sample code:

private void setDrawable(final Menu menu) {
    if (menu == null || menu.size() == 0) return;

    Utils.postToUiHandler(new Runnable() {
        @Override
        public void run() {
            int size = menu.size();
            for (int i = 0; i < size; i++) {
                MenuItem menuItem = menu.getItem(i);
                if (menuItem != null) {
                    View view = activity.findViewById(menuItem.getItemId());
                    if (view != null) {
                        Drawable drawable = ThemeDrawables.get(ThemeWorker.Segment.DEFAULT).actionbarButton();
                        if (drawable != null && view.getBackground() != drawable) {
                            int sdk = android.os.Build.VERSION.SDK_INT;
                            if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                                view.setBackgroundDrawable(drawable);
                            } else {
                                view.setBackground(drawable);
                            }
                        }

                    }
                }
            }
        }
    });

}

Please note, I make findViewById in the UI thread as menuitem' view is not inflated so the should be running in the UI thread


You can get the view using the menu item id, by getting it in onOptionsItemSelected ..

findViewById(R.id.menu_item);

Tags:

Android