findViewById for MenuItem returns null

|▌冷眼眸甩不掉的悲伤 提交于 2020-05-11 03:46:07

问题


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.


回答1:


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



回答2:


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.




回答3:


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



回答4:


Try

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

for me works.



来源:https://stackoverflow.com/questions/16500415/findviewbyid-for-menuitem-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!