将最新的支持库添加到您应用的 build.gradle 依赖项中:
compile 'com.android.support:appcompat-v7:26.0.2'
并在同一文件中添加以下行:
android {
...
defaultConfig {
...
vectorDrawables.useSupportLibrary = true
}
...
}
通过Vector Asset Studio导入矢量图。
就是这样,你准备好了!
图像视图
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。第二个 - to define a custom TextView。
以编程方式
直接设置资源是不行的,你必须使用Drawable对象。以与ImageView 相同的方式获取并使用适当的方法进行设置:
textView.setCompoundDrawablesWithIntrinsicBounds(vectorDrawable, null, null, null);
菜单图标
没有什么特别的:
<item
...
android:icon="@drawable/your_vector"
... />
menuItem.setIcon(R.drawable.your_vector);
通知:
它是impossible,你必须使用 PNG :(