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.
findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .
. findViewById(R. id. retry) would always return null.
FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.
Safe code using binding objectsfindViewById is the source of many user-facing bugs in Android. It's easy to pass an id that's not in the current layout — producing null and a crash. And, since it doesn't have any type-safety built in it's easy to ship code that calls findViewById<TextView>(R. id.
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);
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With