[英]How Fix Package name 'android.support.graphics.drawable' used in: com.android.support:animated-vector-drawable:28.0.0
[英]How to properly use backwards compatible Vector Drawable with the latest Android Support Library?
不久之前,矢量drawable已添加到支持库中,从那时起API中发生了很多变化:Gradle标志,初始化块,选择器,自定义XML属性等。问题是 - 如何正确使用它(在这些情况下支持lib v25):
XML和编程。
将最新的支持lib添加到应用程序的build.gradle
依赖项:
compile 'com.android.support:appcompat-v7:26.0.2'
并在同一文件中添加以下行:
android {
...
defaultConfig {
...
vectorDrawables.useSupportLibrary = true
}
...
}
通过矢量资产工作室导入矢量图像。
就是这样,你准备好了!
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));
XML
没有简单的解决方案:XML属性android:drawableTop(Bottom etc)
无法处理前Lollipop上的矢量图像。 一种解决方案是将初始化块添加到活动并将向量包装到另一个XML drawable中 。 第二 - 定义自定义TextView 。
编程
直接设置资源不起作用,您必须使用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" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.