1

我想为其选中和未选中状态设置一个以编程方式创建的可绘制单选按钮,但它不起作用我的代码如下,

绘制矩形框的代码,

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) 以设置为单选按钮的代码,

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) {
    }
}
4

1 回答 1

1

经过一些工作后,我意识到问题是drawable没有任何大小。我不确定您应该给出什么尺寸,但只需添加以下行即可使您RadioButton可见:

shape.setSize(50, 50);

我建议为其放入适当的尺寸dimens.xml并改用它:

int size = context.getResources().getDimensionPixelSize(R.dimen.radio_button_size);
shape.setSize(size, size);
于 2016-04-19T08:25:35.667 回答