以编程方式为单选按钮设置自定义绘制图形

3
我正在开发一个基本的安卓绘画应用,但是我无法通过编程方式为我的单选按钮设置自定义绘制。这些单选按钮由一个LayerDrawable组成,其中包含白色ColorDrawable作为边框和插入的黄色(或其他颜色)ColorDrawable作为中心。我将这个LayerDrawable与另一个(它具有黑色边框以指示选择)放在StateListDrawable中以保留RadioButton功能。

但是当我尝试使用setButtonDrawable(myDrawable)时,RadioButton仅占据非常小的区域,即使我将宽度和高度指定为30dp

然后,当我尝试使用setButtonDrawable(null)setBackground(myDrawable)时,我的RadioButton不再具有其功能。

以下是我的代码:

private void setupColorButtons() {
    int[] colors = {Color.RED, Color.GREEN, Color.BLUE,
                    Color.YELLOW, Color.CYAN, Color.MAGENTA};
    int childCount = mColorGroup.getChildCount();
    for (int i = 0; i < childCount; i++) {
        RadioButton colorButton = (RadioButton) mColorGroup.getChildAt(i);
        colorButton.setButtonDrawable(createColorButtonDrawable(colors[i]));
    }
}

private Drawable createColorButtonDrawable(int color) {
    ColorDrawable center = new ColorDrawable(color);
    ColorDrawable selBorder = new ColorDrawable(R.color.black);
    ColorDrawable unselBorder = new ColorDrawable(R.color.white);

    LayerDrawable sel = new LayerDrawable(new Drawable[] {selBorder, center});
    sel.setLayerInset(1, 2, 2, 2, 2);
    LayerDrawable unsel = new LayerDrawable(new Drawable[] {unselBorder, center});
    unsel.setLayerInset(1, 2, 2, 2, 2);

    StateListDrawable states = new StateListDrawable();
    states.addState(new int[] {android.R.attr.state_checked}, sel);
    states.addState(new int[] {-android.R.attr.state_checked}, unsel); 
    return states;
}

我已经查看了类似的问题,但每个解决方案都要求我创建自定义xml样式。我只是想知道是否有人知道如何在程序中设置自定义的StateListDrawable。提前感谢任何帮助!

2个回答

3

试试这段代码:

StateListDrawable mState1 = new StateListDrawable();
mState1.addState(new int[] { android.R.attr.state_pressed },
    getResources().getDrawable(R.drawable.button3_pressed));
mState1.addState(new int[] { android.R.attr.state_focused },
    getResources().getDrawable(R.drawable.button3_focused));
mState1.addState(new int[] {},
    getResources().getDrawable(R.drawable.button3_up));
myButton.setBackgroundDrawable(mState1);

1
这是对Leo回答的补充。如果你想要一个假的状态,例如一个禁用的按钮,没有状态 - android.R.attr.state_disabled,所以你可以使资源引用变成负数(在前面加“-”):
state.addState(new int[]{android.R.attr.state_checked,-android.R.attr.state_enabled},...);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接