概述
完全取代简单的图标,在各种分辨率的屏幕上都不会失真.
使用步骤
1.先在gradle里配置参数
目的是让矢量图在5.0前的手机上也正常显示
apply plugin: 'com.android.library'
android {
... ...
defaultConfig {
//配置这个参数
vectorDrawables.useSupportLibrary = true
}
... ...
}
2.drawable –> 右键 –> new –> vector assets里建好。
(0)首先给布局指定命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"
(1)给控件指定矢量图,必须下面用的方式。
app:srcCompat="@drawable/ic_xxx"
例如:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/fab_margin"
android:tint="@android:color/white"
app:backgroundTint="@android:color/holo_orange_light"
app:layout_anchor="@id/app_bar"
app:layout_anchorGravity="bottom|end"
app:srcCompat="@drawable/ic_add" />
</android.support.design.widget.CoordinatorLayout>
3.为矢量图动态设置颜色
(1)静态
如果需要静态指定颜色,在使用的地方给tint属性赋值。
android:tint="@android:color/white"
(2)动态
在需要的地方调用该方法
/**
* 给使用了矢量图的ImageView设置颜色
*
* @param context 上下文
* @param vectorRid xml矢量图的id
* @param colorRid 颜色的id
* @param imageView 要设置的控件
*/
public static void setVectorColorImgv(Context context, int vectorRid, int colorRid, ImageView imageView) {
VectorDrawableCompat vectorDrawableCompat = VectorDrawableCompat.create(context.getResources(),
vectorRid, context.getTheme());
//以下三种方式选一种
//1.设置单一的颜色
vectorDrawableCompat.setTint(context.getResources().getColor(colorRid));
//2.设置状态性的,比如点击一个颜色,未点击一个颜色
//vectorDrawableCompat.setTintList(ColorStateList.valueOf(colorRid));
//3.用这个v4提供的也可,这个适用于任意的drawable着色
//DrawableCompat.setTint(vectorDrawableCompat,.getResources().getColor(colorRid));
imageView.setImageDrawable(vectorDrawableCompat);
}
例如:
//图片初始化
Utils.setVectorColorImgv(this, R.drawable.ic_index, R.color.deep_grey, imgvBottomMainIndex);