问题
I just would like to tweak the View of an ActionBar MenuItem by code.
Unfortunately, it seems that getActionView always return null!
My code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = this.getSupportMenuInflater();
inflater.inflate(R.menu.folder, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onPrepareOptionsMenu(final Menu menu) {
MenuItem menuFolder = menu.findItem(R.id.menu_folder);
Log.i("", "* onPrepareOptionsMenu *" + menuFolder);
Log.i("", "* getActionView *" + menuFolder.getActionView());
Log is:
01-11 22:13:42.884: I/(7893): * onPrepareOptionsMenu *com.actionbarsherlock.internal.view.menu.MenuItemWrapper@41401ac8
01-11 22:13:42.884: I/(7893): * getActionView *null
Thank a lot for any help
Edit:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_folder"
android:icon="@drawable/ic_menu_archive"
android:showAsAction="always"/>
</menu>
回答1:
getActionView() only works if there's a custom actionView from setActionView.
回答2:
you should use
app:actionLayout="@layout/menu_actionbar_basket"
thats the trick if you use
android:actionLayout="@layout/menu_actionbar_basket"
you would always get null exception in default toolbar.
回答3:
For me the solution that worked is to use app namespace instead of android.
app:actionViewClass="android.support.v7.widget.SearchView"
Don't forget to declare it:
xmlns:app="http://schemas.android.com/apk/res-auto"
回答4:
If your debug build is working without any issues and issue is only with release build then this may be because of proguard configuration. If you have enabled proguard in your application then add below line to proguard-rules.pro
-keep class android.support.v7.widget.SearchView { *; }
来源:https://stackoverflow.com/questions/14286768/getactionview-of-my-menuitem-return-null