getActionView() of my MenuItem return null

2019-01-09 17:13发布

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>

4条回答
聊天终结者
2楼-- · 2019-01-09 17:49

getActionView() only works if there's a custom actionView from setActionView.

查看更多
放我归山
3楼-- · 2019-01-09 17:56

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"

查看更多
Anthone
4楼-- · 2019-01-09 17:57

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.

查看更多
地球回转人心会变
5楼-- · 2019-01-09 17:59

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 { *; }
查看更多
登录 后发表回答