findViewById for MenuItem returns null

yasith picture yasith · May 11, 2013 · Viewed 18.8k times · Source

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.

Answer

Hoan Nguyen picture Hoan Nguyen · May 11, 2013

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);