yasith
yasith

Reputation: 9501

findViewById for MenuItem returns null

This is my xml file for the ActionBar menu.

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
            android:id="@+id/fav_button"
            android:title="Favourite"
            android:icon="@drawable/unstar"
            android:showAsAction="always|withText" />
</menu>

In my onCreate function, after calling setContentView. I do favButton = (MenuItem) this.findViewById(R.id.fav_button); But this returns null.

But returns the proper object on the onOptionsItemSelected function.

I'm using ActionBarSherlock, if that would make a difference.

I have tried various options suggested by other findViewById returns null questions, but they haven't solved my issue.

Upvotes: 27

Views: 22772

Answers (5)

Infinity_zhang
Infinity_zhang

Reputation: 112

I don't know why, but in my case, I use findViewById(R.id.menu_id) return null. But I find that I use findViewById(item.getItemId) in onOptionsItemSelected, it return the view what we want.

Upvotes: 0

Paolo
Paolo

Reputation: 43

Try

        final Toolbar toolbar = findViewById(R.id.toolbar);
        Menu menu=toolbar.getMenu();
        MenuItem item = menu.findItem(R.id.'name id item');

for me works.

Upvotes: 0

user25
user25

Reputation: 3195

but if someone really needs View and not MenuItem (for different manipulations, for example to start animation) you can still get it the next way:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.your_menu_xml_file, menu);
    ...
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            view = findViewById(R.id.menu_refresh_button);
            // view.startAnimation(animation);
        }
    });
    return true;
}

Upvotes: 1

onusopus
onusopus

Reputation: 1244

Use menu.findItem() to get the menu. But this needs to be done after the menu is inflated.

Also, to answer your q in comment, you could use onPrepareOptionsMenu to set the state of your menu. If this menu is a one time updating, you could use onCreateOptionsMenu too, which is called only once.

Upvotes: 3

Hoan Nguyen
Hoan Nguyen

Reputation: 18151

Instead of

favButton = (MenuItem) this.findViewById(R.id.fav_button);  

in onCreateOptionsMenu after getMenuInflater().inflate(R.menu.activity_main, menu);

favButton = menu.findItem(R.id.fav_button);

Upvotes: 51

Related Questions