I want to change my icon color from my button programmatically...
On my xml, i have:
android:drawableTint="@color/colorPrimary"
android:drawableTop="@drawable/ic_car_black_24dp"
To set the icon and set the icon color... But i want to change the icon color from my java side...
Can someone help me?
<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" />
First of all, do not use AppCompatButton directly unless you write a custom view and you want to extend it. The normal Button will be "resolved" by the system as AppCompatButton so you don't need the latter.
As for your original question, there are multiple ways to tint a drawable. You can use DrawableCompact to do it in a "tinting" fashion while you can use a normal ColorFilter to do this in a "filtering" fashion.
DrawableCompat
Use DrawableCompat to wrap the drawable so it can be tinted on older platforms.
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
Use the Drawable.setColorFilter(...) method to set an overlaying color filter for your 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);
Use setCompoundDrawableTintList property to change color i use it as following
btn_recent.setCompoundDrawableTintList(ColorStateList.valueOf(Color.parseColor("#ff9708")));
I use vector drawable as drawableLeft for the Button and changed the button drawable colour programmatically using Kotlin like this.
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));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With