如何正确使用向后兼容的 Vector Drawable 和最新的 Android 支持库?

How to properly use backwards compatible Vector Drawable with the latest Android Support Library?

矢量可绘制对象不久前被添​​加到支持库中,API 从那时起发生了很多变化:Gradle 标志、初始化程序块、选择器、自定义 XML 属性等。问题是 - 在这些情况下如何正确使用它(支持 lib v25):

XML 和编程方式。

将最新的支持库添加到您应用的 build.gradle 依赖项中:

compile 'com.android.support:appcompat-v7:26.0.2'

并在同一文件中添加以下行:

android {
    ...
    defaultConfig {
        ...
        vectorDrawables.useSupportLibrary = true
    }
    ...
}

通过Vector Asset Studio导入矢量图。

就这样,你准备好了!


ImageView

XML

使用 app:srcCompat 属性代替 android:src:

<ImageView
    ...
    app:srcCompat="@drawable/your_vector" 
    ... />

以编程方式

直接来自资源id:

imageView.setImageResource(R.drawable.your_drawable);

设置为 Drawable 对象(例如用于着色):

Drawable vectorDrawable 
                = AppCompatResources.getDrawable(context, R.drawable.your_vector);
imageView.setImageDrawable(vectorDrawable);

如果您想设置色调:

DrawableCompat.setTint
             (vectorDrawable, ContextCompat.getColor(context, R.color.your_color));

可绘制的 TextView

XML

没有简单的解决方案:XML 属性 android:drawableTop(Bottom etc) 无法处理 pre-Lollipop 上的矢量图像。一种解决方案是 add initializer block to activity and wrap vector into another XML drawable. Second - .

以编程方式

直接设置资源是不行的,你必须使用Drawable对象。获取方式与 ImageView 相同,并使用适当的方法进行设置:

textView.setCompoundDrawablesWithIntrinsicBounds(vectorDrawable, null, null, null);

菜单图标

没有什么特别的:

<item
    ...
    android:icon="@drawable/your_vector"
    ... />

menuItem.setIcon(R.drawable.your_vector);

通知:

它是 ,你必须使用 PNG :(

您需要将 vectorDrawables.useSupportLibrary = true 添加到您的 build.gradle 文件中:

// Gradle Plugin 2.0+  
 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
    }  
 } 

您会注意到此新属性仅存在于 Gradle 插件的 2.0 版中。如果您使用的是 Gradle 1.5,您将改为使用:

// Gradle Plugin 1.5  
 android {  
   defaultConfig {  
     generatedDensities = []  
  }  

  // This is handled for you by the 2.0+ Gradle Plugin  
  aaptOptions {  
    additionalParameters "--no-version-vectors"  
  }  
 }  

您需要将 srcCompat 添加到您的 ImageView:

<ImageView  
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  app:srcCompat="@drawable/ic_add" />