How can I use VectorDrawable with the Android Toolbar?

不羁岁月 提交于 2019-12-03 04:33:50

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 %)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!