Programmatically setting Button Background Drawabl

2019-08-30 02:54发布

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条回答
淡お忘
2楼-- · 2019-08-30 03:09

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;

    }
查看更多
太酷不给撩
3楼-- · 2019-08-30 03:10

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
    
查看更多
Evening l夕情丶
4楼-- · 2019-08-30 03:28

Use Mode.SRC instead of Mode.SRC_IN.

See the PorterDuff modes for more details.

查看更多
登录 后发表回答