Search code examples
androidandroid-toolbarandroid-vectordrawable

How can I use VectorDrawable with the Android Toolbar?


What is the proper method to use the new VectorDrawable in the toolbar?

I tried to use the app:srcCompat element as illustrated below, but nothing showed up.

<menu
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto">
  <item
    app:srcCompat="@drawable/ic_clear"
    app:showAsAction="ifRoom" />
</menu>

I have my own toolbar layout using android.support.v7.widget.Toolbar and Android Support Library v23.2 on JB (16).


Solution

  • Turns out it's quite easy. Say, you have vector drawable vd_trash_24dp.

    Describing MenuItem one cannot address VectorDrawable directly with android:icon. It seems ignoring app:srcCompat also.

    But. As all we know ;)

    AppCompat does support loading vector drawables when they are referenced in another drawable container such as a StateListDrawable, InsetDrawable, LayerDrawable, LevelListDrawable, and RotateDrawable

    Let's try it, should we?

    Create StateListDrawable vd_test_vd

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/vd_trash_24dp" />
    
    </selector>
    

    than

    <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">
        <item android:id="@+id/menu_action_filter"
              android:title="@string/menu_action_filter"
              android:icon="@drawable/vd_test_vd"
              android:orderInCategory="100"
              app:showAsAction="always"/>
    </menu>
    

    street magic indeed.

    Yes, one could try and set drawable at runtime with MenuItem.setIcon(). But who need that %)