Android使用Tint,只用一张图片显示不同状态下的颜色

本文介绍如何利用Tint减少APK文件大小,通过一张图片实现多种颜色变化,并提供了一种解决selector.xml中状态颜色切换问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为了使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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值