Search code examples
androidandroid-custom-view

How to get and change drawable background color in custom view


I have a custom view which extends TextView and the background is a drawable,

<CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/circile_background" />

and want to change the background color in custom view

public class CustomView extends TextView {

    TypedArray typedArray;

    public CustomView (Context context) {
        super(context);
    }

    public CustomView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public void setColorLevel(int color) {
       // update color here
    }
}

Solution

  • check similar question here How to change colors of a Drawable in Android?

    public void setDangerLevel(int color) {
        Drawable drawable=this.getBackground().getCurrent();
        drawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
        }