我想以编程方式从我的按钮更改我的图标颜色...
在我的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
来wrap drawable所以它可以是旧平台上的tinted。
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(...)
方法为drawable设置重叠的滤色器。
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")));
我假设您需要更改android:drawableTint
属性。
根据this,你需要创建一个具有不同色调的新drawable,然后更改按钮的drawable资源。
从你的图标创建一个Drawable
:
Drawable mDrawable=getContext().getResources().getDrawable(R.drawable.ic_car_black_24dp);
然后改变它的色调:
mDrawable.setColorFilter(new PorterDuffColorFilter(0xffff00,PorterDuff.Mode.MULTIPLY));
你已经完成了这个,设置你的新Drawable
:
yourButton.setImageDrawable(mDrawable);
我建议你浏览链接问题和here in the docs的评论,以发现不同的PorterDuff
模式。
你可能想根据你的问题通过kotlin数据绑定适配器动态检查我的方法来更改按钮颜色。看看here
我还提到并参考了原始答案以及替代解决方案的文章或更好地理解变通方法