如何正确使用向后兼容的 Vector Drawable 与最新的 Android 支持库? [英] How to properly use backwards compatible Vector Drawable with the latest Android Support Library?
问题描述
Vector drawable 不久前被添加到支持库中,从那时起 API 发生了很多变化:Gradle 标志、初始化块、选择器、自定义 XML 属性等.问题是 - 如何正确使用在这些情况下,它现在(支持 lib v25):
Vector drawable has been added to Support Library not so long time ago and there were a lot of changes in the API since then: Gradle flags, initializer blocks, selectors, custom XML attributes etc. The question is - how to properly use it now (support lib v25) in these cases:
- 图像视图
- TextView 可绘制
- 菜单图标
- 通知图标
XML 和编程方式.
推荐答案
将最新的支持库添加到您应用的 build.gradle
依赖项:
Add the latest support lib to your app's build.gradle
dependencies:
compile 'com.android.support:appcompat-v7:26.0.2'
并在同一文件中添加以下行:
and add the following line in the same file:
android {
...
defaultConfig {
...
vectorDrawables.useSupportLibrary = true
}
...
}
通过 Vector Asset Studio 导入矢量图像.
Import vector image through Vector Asset Studio.
就是这样,你准备好了!
XML
使用 app:srcCompat
属性代替 android:src
:
<ImageView
...
app:srcCompat="@drawable/your_vector"
... />
以编程方式
直接来自资源 ID:
imageView.setImageResource(R.drawable.your_drawable);
设置为 Drawable
对象(例如用于着色):
Set as Drawable
object (e.g. for tinting):
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)
无法处理预棒棒糖上的矢量图像.一种解决方案是 将初始化块添加到活动并将 vector 包装到另一个 XML drawable 中.第二 - 定义自定义 TextView.
There is no simple solution: XML attribute android:drawableTop(Bottom etc)
can't handle vector images on pre-Lollipop. One solution is to add initializer block to activity and wrap vector into another XML drawable. Second - to define a custom TextView.
以编程方式
直接设置资源不行,必须使用Drawable
对象.以与 ImageView
相同的方式获取它并使用适当的方法设置它:
Setting resource directly doesn't work, you have to use Drawable
object. Get it the same way as for ImageView
and set it with the appropriate method:
textView.setCompoundDrawablesWithIntrinsicBounds(vectorDrawable, null, null, null);
<小时>
菜单图标
没什么特别的:
<item
...
android:icon="@drawable/your_vector"
... />
menuItem.setIcon(R.drawable.your_vector);
<小时>
通知:
不可能,您必须使用 PNG :(
Notifications:
It's impossible, you have to use PNGs :(
这篇关于如何正确使用向后兼容的 Vector Drawable 与最新的 Android 支持库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!