androidandroid-actionbaractionbarsherlock

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.


Solution

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