MenuItem的findViewById返回null

yas*_*ith 24 android actionbarsherlock android-actionbar

这是ActionBar菜单的xml文件.

<?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>
Run Code Online (Sandbox Code Playgroud)

在我的onCreate功能,打电话setContentView.我这样做favButton = (MenuItem) this.findViewById(R.id.fav_button);但是这会返回null.

但是返回onOptionsItemSelected函数上的正确对象.

我正在使用ActionBarSherlock,如果这会有所作为.

我尝试了其他findViewById建议的各种选项返回null问题,但他们还没有解决我的问题.

Hoa*_*yen 41

代替

favButton = (MenuItem) this.findViewById(R.id.fav_button);  
Run Code Online (Sandbox Code Playgroud)

在getMenuInflater().inflate之后的onCreateOptionsMenu中(R.menu.activity_main,menu);

favButton = menu.findItem(R.id.fav_button);
Run Code Online (Sandbox Code Playgroud)

  • 在onCreate期间没有办法获得它吗?我希望能够基于savedInstanceState Bundle setChecked().或者,是否有更好的方法来保存MenuItem的旋转状态? (2认同)