设置自定义以编程方式创建drawable到radioButton状态

时间:2016-04-19 07:21:16

标签: android android-custom-view android-drawable android-radiobutton android-custom-drawable

我想设置一个以编程方式创建的drawable到单选按钮,用于其已检查和未检查的状态,但它不起作用我的代码如下,

绘制矩形框的代码,

public static GradientDrawable squareView(int backgroundColor, int borderColor)
{
    GradientDrawable shape = new GradientDrawable();
    shape.setShape(GradientDrawable.RECTANGLE);
    //shape.setCornerRadii(new float[] { 8, 8, 8, 8, 0, 0, 0, 0 });
    shape.setColor(backgroundColor);
    shape.setStroke(3, borderColor);
    return shape;
}

设置以编程方式创建的View(squareview)设置为radiobutton所述的代码,

public static void setChecked_Selector(Context context,RadioButton view) {
    try {
        Drawable pressed=squareView(ContextCompat.getColor(context,R.color.colorBlue),ContextCompat.getColor(context,R.color.colorRed));//new BadgeDrawable(context,colorPressed);
        Drawable normal=squareView(ContextCompat.getColor(context,R.color.colorwhite),ContextCompat.getColor(context,R.color.colorRed));

        StateListDrawable states = new StateListDrawable();
        states.addState(new int[]{android.R.attr.state_checked,},pressed);
        states.addState(new int[]{android.R.attr.state_pressed}, pressed);

        states.addState(new int[]{android.R.attr.state_checked, android.R.attr.state_enabled}, pressed);
        states.addState(new int[]{android.R.attr.state_checked, -android.R.attr.state_enabled}, pressed);

        states.addState(new int[]{}, normal);
        view.setButtonDrawable(states);
    } catch (Exception e) {
    }
}

1 个答案:

答案 0 :(得分:1)

经过一番努力,我意识到问题是drawable没有任何尺寸。我不确定您应该给出的尺寸,但只需添加以下行就可以显示RadioButton

shape.setSize(50, 50);

我建议在dimens.xml中为其添加适当的大小并改为使用:

int size = context.getResources().getDimensionPixelSize(R.dimen.radio_button_size);
shape.setSize(size, size);