Skip to content Skip to sidebar Skip to footer

Programmatically Setting Button Background Drawable Color

I have a drawable created beforehand which is a shape of rectangle but is fully transparent. Now I would like to assign this drawable to the Button in code but also set the Color

Solution 1:

Use Mode.SRC instead of Mode.SRC_IN.

See the PorterDuff modes for more details.

Solution 2:

Finally I got the end results using a 2 step solution -

  1. I fixed the drawable from being a transparent one to pure white one with no opacity (it seems the color Filtering / tinting, works best on whites)

  2. I also used the below lines of code to do the trick -

    Drawabledrawable= ResourcesCompat.getDrawable(context.getResources(), R.drawable.yourcustomshape, null);
    
        drawable = DrawableCompat.wrap(drawable);
    
        DrawableCompat.setTintList(drawable, ColorStateList.valueOf(Color.BLUE)); // Can be any color you need to color the shape

Solution 3:

Using Two Methods You can Set background color and Border

This For Without background Color

publicstatic GradientDrawable backgroundWithoutBorder(int color){

        GradientDrawable gdDefault = newGradientDrawable();
        gdDefault.setColor(color);
        gdDefault.setCornerRadii(newfloat[] { radius, radius, 0, 0, 0, 0,
                radius, radius });
        return gdDefault;

    }

This For With background Color

publicstatic GradientDrawable backgroundWithBorder(int bgcolor,
            int brdcolor){

        GradientDrawable gdDefault = newGradientDrawable();
        gdDefault.setColor(bgcolor);
        gdDefault.setStroke(2, brdcolor);
        gdDefault.setCornerRadii(newfloat[] { radius, radius, 0, 0, 0, 0,
                radius, radius });

        return gdDefault;

    }

Post a Comment for "Programmatically Setting Button Background Drawable Color"