如何正确使用向后兼容的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:
- ImageView
- TextView drawable
- 菜单图标
- 通知图标
- ImageView
- TextView drawable
- Menu icon
- Notification icon
XML和编程方式。
XML and programmatically.
推荐答案
将最新的支持库添加到应用程序的 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 。
这就是全部,你准备好了!
XML
使用 app:srcCompat
属性而不是 android:src
:
<ImageView
...
app:srcCompat="@drawable/your_vector"
... />
以编程方式
直接来自资源ID:
imageView.setImageResource(R.drawable.your_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 drawable
XML
没有简单的解决方案:XML属性 android:drawableTop(Bottom等) )
无法处理前Lollipop上的矢量图像。一种解决方案是将初始化程序块添加到活动中并将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);
菜单图标
没有什么特别之处:
Menu icon
There is nothing special:
<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屋!