Search code examples
androidxmlandroid-layoutandroid-spinnerandroid-toolbar

Change Spinner dropdown icon in toolbar


I'm trying to use an icon in the toolbar as a Spinner... This is my menu.xml:

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_search_cat"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:title=".."/>
    <item
        android:id="@+id/action_filter_rating"
        app:showAsAction="always"
        android:actionViewClass="android.widget.Spinner"
        android:icon="@drawable/ic_star" // THIS LINE HAVE NO EFFECT 
        android:title=".." />
    <item
        android:id="@+id/action_manage_category"
        android:title=".."
        app:showAsAction="never" />
    <item
        android:id="@+id/action_export_csv"
        android:title="@string/export"
        app:showAsAction="never" />

Right now the dropdown icon is the default one (android.widget.Spinner), is there a way to override that icon? I want to keep the spinner in the items of the menu. I want to change this icon:

enter image description here

I will accept every other solution to achieve a custom icon in the toolbar, in the same position, working as a Spinner (with dropdown). Thank you!


Solution

  • On MenuItem click you can inflate PopupMenu, which behaves like a Spinner.

    menu.xml:

        <item
        android:id="@+id/action_filter_rating"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_collections_white_24dp"
        android:enabled="true"
        android:title="@string/action_filter_rating"/>
    

    Activity menu listener:

     @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_filter_rating) {
            View anchor = findViewById(R.id.action_filter_rating);
            PopupMenu popup = new PopupMenu(this, anchor);
            popup.getMenuInflater().inflate(R.menu.your_spinner_menu, popup.getMenu());
            popup.getMenu().add("You can dynamically add items");
            popup.setOnMenuItemClickListener(...);
            popup.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }