Programmatically setting Button Background Drawable Color

936 Views Asked by At

square_transparent.png

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 of this drawable from transparent to some specific color like Orange etc.

I have already tried setting the same using some other posts like -

Drawable mDrawable = ContextCompat.getDrawable(this, R.drawable.square_transparent); 
    mDrawable.setColorFilter(
                    new PorterDuffColorFilter(
                            Color.Orange, Mode.SRC_IN)
                            );

but it doesn't work. When the activity renders the button ,it is still transparent only.

I also tried explicitly setting the mDrawable.setAlpha to 255 (fully opaque) before assigning the drawable to the button, but even that doesn't work.

Please suggest, if anyone has this working in some other fashion.

3

There are 3 best solutions below

1
On

Use Mode.SRC instead of Mode.SRC_IN.

See the PorterDuff modes for more details.

0
On

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 -

        Drawable drawable = 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
    
0
On

Using Two Methods You can Set background color and Border

This For Without background Color

public static GradientDrawable backgroundWithoutBorder(int color) {

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

    }

This For With background Color

    public static GradientDrawable backgroundWithBorder(int bgcolor,
            int brdcolor) {

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

        return gdDefault;

    }