aez aez - 5 months ago 24
Android Question

Can't get action view for ActionBar MenuItem using support library

I recently switched from ActionBarSherlock to the Android support library action bar, and now I get a null on the action view of a spinner in the action bar. Here's the code as suggested by the docs:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
MenuItem spinnerItem = menu.findItem(R.id.menuNavigateType);
View view = MenuItemCompat.getActionView(spinnerItem);// !! view is NULL !!
...
}


Here's R.menu.home_menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res-auto">
...
<item
android:id="@+id/menuNavigateType"
myapp:showAsAction="always"
myapp:actionViewClass="android.support.v7.widget.Spinner" />
...
</menu>


How do I get my action view?

Thanks.

Answer

Not sure, but try the following, instead of MenuItemCompat.getActionView(), use:

@Override
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.home_menu, menu);   
    MenuItem spinnerItem = menu.findItem(R.id.menuNavigateType);

    View view = spinnerItem.getActionView();
    // ...
    if(view instanceof Spinner) {
        final Spinner spinner = (Spinner) view;
        // create your adapter
        // ...
        // set your adapter
        spinner.setAdapter(adapter);
    }
}

Also for your item, instead of android.support.v7.widget.Spinner:

<item
    android:id="@+id/menuNavigateType"
    myapp:showAsAction="always"
    myapp:actionViewClass="android.widget.Spinner" >  

I saw this solution here: Android ActionBar (ActionBarCompat) Spinner Dropdown list ?.
Let me know if it helps you.