How can I use VectorDrawable with the Android Toolbar?

喜夏-厌秋 提交于 2019-12-03 14:45:16

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/35813199/how-can-i-use-vectordrawable-with-the-android-toolbar

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