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

2024-01-06

我正在 Android 中开发一个基本的绘画应用程序,但我似乎无法以编程方式为我的单选按钮设置自定义绘图。这些单选按钮由LayerDrawable与一个白色的ColorDrawable对于边框和插入黄色(或任何颜色)ColorDrawable为中心。我把这个LayerDrawable与另一个(它有黑色边框表示选择)一起在StateListDrawable以保存RadioButton功能。

但当我尝试时setButtonDrawable(myDrawable), the RadioButton尽管我指定了宽度和高度,但占用的区域非常小30dp.

然后当我尝试时setButtonDrawable(null) and setBackground(myDrawable), my 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以编程方式。预先感谢您的任何帮助!


试试这个代码:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式设置单选按钮的自定义绘图 的相关文章