如何在Android API低于21的情况下使用VectorDrawables?

77

我正在开发一个Android项目,并选择使用<vector>来显示图标,因为它是适配和动态的,但是我只能在运行Android系统API版本21或更高版本的设备上运行此应用程序。我的问题是如何在低版本的Android系统(例如API 14或类似版本)上使用<vector>。谢谢!

<!-- drawable/ic_android_debug_bridge.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="48dp"
    android:width="48dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path android:fillColor="@color/primaryColorDark"
        android:pathData="M15,9A1,1 0 0,1 14,8A1,1 0 0,1 15,7A1,1 0 0,1 16,8A1,1 `0 0,1 15,9M9,9A1,1 0 0,1 8,8A1,1 0 0,1 9,7A1,1 0 0,1 10,8A1,1 0 0,1 9,9M16.12,4.37L18.22,2.27L17.4,1.44L15.09,3.75C14.16,3.28 13.11,3 12,3C10.88,3 9.84,3.28 8.91,3.75L6.6,1.44L5.78,2.27L7.88,4.37C6.14,5.64 5,7.68 5,10V11H19V10C19,7.68 17.86,5.64 16.12,4.37M5,16C5,19.86 8.13,23 12,23A7,7 0 0,0 19,16V12H5V16Z" /></vector>

如何使用向量的实际信息 - https://dev59.com/Hpzha4cB1Zd3GeqPHp7S - Maksim Ostrovidov
13个回答

2

为了让@2Dee的回答更加完整:

VectorDrawable不能在API 20及以下版本中使用。官方方法生成png,然后成为BitmapDrawables,这破坏了矢量图形的概念。

个人更喜欢svg而非xml向量:

  • 这样的图形可以直接从Illustrator或其他流行软件导出
  • svg支持变换、文本、蒙版和其他一些东西
  • 所有平台上真正可缩放的矢量图形
  • 尺寸更小,构建速度更快

要使用矢量图形,您可以尝试https://github.com/BigBadaboom/androidsvg。这是一个svg阅读器和svg兼容的ImageView。


1

在gradle默认设置中设置vectorDrawables.useSupportLibrary = true,并在activity on create中设置AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);,以避免与TextView中的android:drawableLeft 崩溃。例如,将drawable left编程设置到TextView中:

 textview.setCompoundDrawablesWithIntrinsicBounds(R.drawable.movie, 0, 0, 0);

0

我也遇到了同样的问题。然后我做了以下操作:

vectorDrawables.useSupportLibrary = true

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

textview.setCompoundDrawablesWithIntrinsicBounds(R.drawable.movie, 0, 0, 0);

这个方法很好。但是之后,我遇到了一个资源找不到的错误。
所以我发现根据SDK版本添加矢量图像会更好。

最终,这个解决方案对我来说非常好:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    textview.setCompoundDrawablesWithIntrinsicBounds(null, null, AppCompatResources.getDrawable(this, R.drawable.movie), null);
} else {
    textview.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.movie, 0);
}
  • 我希望它能帮助到某人。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接