Preface
This article mainly introduces the relevant content of the image DrawableCompat in Android using setTint() to change the color of the image Drawable. It is shared for your reference and learning. I won’t say much below. Let’s take a look at the detailed introduction together:
1. Use color resources to change color to Drawable
The source of the Drawable object is not limited, it can be obtained from the resource getResource().getDrawable(int resourceId) or other methods.
Drawable wrappedDrawable = (drawable); (wrappedDrawable, color);
2. Use ColorStateList to change Drawable
Drawable wrappedDrawable = (drawable); (wrappedDrawable, colors);
3. Introduction to ColorStateList
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:andro> <item android:state_pressed="true" android:color="#ffff0000"/> <!-- pressed --> <item android:state_focused="true" android:color="#ff0000ff"/> <!-- focused --> <item android:color="#ff000000"/> <!-- default --> </selector>
Java code (used to change the font color of a button)
Button btn=(Button)findViewById(); Resources resource=(Resources)getBaseContext().getResources(); ColorStateList csl=(ColorStateList)(.button_text); if(csl!=null){ (color_state_list);//Set the button text color}
4. Amway a friend encapsulated tool class
public class DrawableTintUtil { /** * Drawable color conversion class * * @param drawable * @param color resources * @return Drawable after changing color */ public static Drawable tintDrawable(@NonNull Drawable drawable, int color) { Drawable wrappedDrawable = (drawable); (wrappedDrawable, color); return wrappedDrawable; } /** * Drawable color conversion class * * @param drawable Source Drawable * @param ColorStateList * @return Drawable after changing color */ public static Drawable tintListDrawable(@NonNull Drawable drawable, ColorStateList colors) { Drawable wrappedDrawable = (drawable); (wrappedDrawable, colors); return wrappedDrawable; } }
Summarize
The above is the entire content of this article. I hope that the content of this article will be of some help to the study or work of Android developers. If you have any questions, you can leave a message to communicate. Thank you for your support.