以编程方式设置按钮背景可绘制颜色 [英] Programmatically setting Button Background Drawable Color

查看:357
本文介绍了以编程方式设置按钮背景可绘制颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个预先创建的drawable,它是矩形形状,但完全透明.现在,我想在代码中将此可绘制对象分配给Button,还要将该可绘制对象的颜色从透明设置为某些特定的颜色,例如橙色等.

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.

我已经尝试使用-

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.

在将可绘制对象分配给按钮之前,我还尝试将mDrawable.setAlpha显式设置为255(完全不透明),但是即使这样也不起作用.

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.

推荐答案

使用两种方法可以设置背景色和边框

Using Two Methods You can Set background color and Border

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;

    }

用于背景颜色

    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;

    }

这篇关于以编程方式设置按钮背景可绘制颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆