[英]Change android button drawable icon color programmatically
我想以编程方式从我的按钮更改我的图标颜色...
在我的 xml 上,我有:
android:drawableTint="@color/colorPrimary"
android:drawableTop="@drawable/ic_car_black_24dp"
设置图标并设置图标颜色...但我想从我的java端更改图标颜色...
有人可以帮助我吗?
<android.support.v7.widget.AppCompatButton
android:id="@+id/bt_search_vehicle_car"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/eight_density_pixel"
android:layout_weight="1"
android:background="@drawable/background_rounded_blue_border"
android:drawableTint="@color/colorPrimary"
android:drawableTop="@drawable/ic_car_black_24dp"
android:padding="@dimen/eight_density_pixel"
android:text="Carros"
android:textAllCaps="false"
android:textColor="@color/colorPrimary" />
首先,不要直接使用AppCompatButton
除非你写了一个自定义视图并且你想扩展它。 普通Button
将被系统“解析”为AppCompatButton
因此您不需要后者。
至于您最初的问题,有多种方法可以为 drawable 着色。 您可以使用DrawableCompact
以“着色”方式执行此操作,而您可以使用普通ColorFilter
以“过滤”方式执行此操作。
DrawableCompat
着色使用DrawableCompat
包装可绘制对象,以便它可以在旧平台上着色。
Button yourButton = findViewById(R.id.bt_search_vehicle_car);
Drawable drawable = getResources().getDrawable(R.drawable.ic_car_black_24dp);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorPrimary));
yourButton.setCompoundDrawables(null, drawable, null, null);
ColorFilter
使用Drawable.setColorFilter(...)
方法为您的可绘制对象设置覆盖颜色过滤器。
Button yourButton = findViewById(R.id.bt_search_vehicle_car);
Drawable drawable = getResources().getDrawable(R.drawable.ic_car_black_24dp).mutate();
drawable.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_ATOP);
yourButton.setCompoundDrawables(null, drawable, null, null);
使用 setCompoundDrawableTintList 属性来改变颜色我使用它如下
btn_recent.setCompoundDrawableTintList(ColorStateList.valueOf(Color.parseColor("#ff9708")));
我使用矢量可绘制作为按钮的 drawableLeft,并像这样使用Kotlin 以编程方式更改按钮可绘制颜色。
button_id.compoundDrawableTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.blue))
public void setTextViewDrawableTintColor(TextView textView, int color) {
for (Drawable drawable : textView.getCompoundDrawables()) {
if (drawable != null) {
drawable.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(textView.getContext(), color), PorterDuff.Mode.SRC_IN));
}
}
}
我假设您需要更改android:drawableTint
属性。
根据这个,你需要创建一个新的可绘制具有不同的色彩,然后更改绘制资源为您的按钮。
从你的图标创建一个Drawable
:
Drawable mDrawable=getContext().getResources().getDrawable(R.drawable.ic_car_black_24dp);
然后改变它的色调:
mDrawable.setColorFilter(new PorterDuffColorFilter(0xffff00,PorterDuff.Mode.MULTIPLY));
你已经完成了这个,设置你的新Drawable
:
yourButton.setImageDrawable(mDrawable);
我建议您浏览链接问题的评论和文档中的此处,以发现不同的PorterDuff
模式。
您可能想根据您的问题检查我通过数据绑定适配器与 kotlin 动态更改按钮颜色的方法。 在这里查看
我还提到并参考了原始答案以及替代解决方案的文章或更好地了解解决方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.