Programmatically setting Button Background Drawable Color

隐身守侯 提交于 2019-12-25 06:59:04

问题


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.


回答1:


Use Mode.SRC instead of Mode.SRC_IN.

See the PorterDuff modes for more details.




回答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 -

        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
    



回答3:


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;

    }


来源:https://stackoverflow.com/questions/32161801/programmatically-setting-button-background-drawable-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!