为了使apk体积尽量的小,使用Tint(着色器)就可以使用一张图片设置不同的颜色。自己记录一下,以方便查阅。
修改图片的背景颜色:
view.setBackgroundDrawable(tintDrawable(drawable,ColorStateList.valueOf(Color.WHITE)));
public static Drawable tintDrawable(Drawable drawable, ColorStateList colors) {
final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTintList(wrappedDrawable, colors);
return wrappedDrawable;
}
以下代码使用了两种切换(状态正常状态和按下状态),通过selector.xml改变不同状态颜色不起作用.不知道为什么。(求告知)
ColorStateList colorStateList = getResources().getColorStateList(R.color.share_fri);
view.setBackgroundDrawable(tintDrawable(drawable,colorStateList);
所以使用以下代码进行设置:
mShareWx_ll.setBackgroundDrawable(tintDrawable(this, R.mipmap.share_fri, R.color.share_, R.color.share_pressed));
private Drawable tintDrawable(Context context, int res, int stateRes, int tatePressedRes) {
Drawable drawable = ContextCompat.getDrawable(context, res);
int[] colors = new int[]{ContextCompat.getColor(context, tatePressedRes), ContextCompat.getColor(context, stateRes)};
int[][] states = new int[2][];
states[0] = new int[]{android.R.attr.state_pressed};
states[1] = new int[]{};
ColorStateList colorStateList = new ColorStateList(states, colors);
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(states[0], drawable);
stateListDrawable.addState(states[1], drawable);
final Drawable.ConstantState constantState = stateListDrawable.getConstantState();
drawable = DrawableCompat.wrap(constantState == null ? stateListDrawable : constantState.newDrawable().mutate());
DrawableCompat.setTintList(drawable, colorStateList);
return drawable;
}