1

I need to get a reference to a MenuItem's corresponding View without specifying a custom one. Using findViewById() with a menu item's ID returns null when called from Activity#onCreate() or onCreateOptionsMenu(). However, as a few answers to other questions point out, findViewById() does return the view when called from onOptionsItemSelected() or from a runnable posted in Activity#onCreate(), like so...

new Handler().post(new Runnable() {
    @Override
    public void run() {
        findViewById(R.id.some_view);
    }
});

So it seems that at some point, Android takes the Menu that you populate in onCreateOptionsMenu() and creates the corresponding Views that are shown on screen. A Runnable posted from onCreate() happens to get run after that happens. But it feels so hacky to assume that will always be the case instead of actually listening for some kind of menuViewsCreated() event.

So that brings me to my question – does Android provide an event that tells developers that the menu Views have been created?

spaaarky21
  • 6,524
  • 7
  • 52
  • 65

1 Answers1

0

It's late but it may help some one else you must use new Handler() in the onCreateOptionsMenu(Menu menu)

@Override
public 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.menu_item);
            //TODO

        }
    });


    return true;
}
Mohamed Ben Romdhane
  • 1,005
  • 3
  • 11
  • 22