我正在尝试以编程方式将一组 RadioButtons 添加到 RadioGroup,如下所示:
for (int i = 0; i < RANGE; i++) {
RadioButton button = new RadioButton(this);
button.setId(i);
button.setText(Integer.toString(i));
button.setChecked(i == currentHours); // Select button with same index as currently selected number of hours
button.setButtonDrawable(Color.TRANSPARENT);
button.setBackgroundResource(R.drawable.selector);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
((RadioGroup)view.getParent()).check(view.getId());
currentHours = view.getId();
}
});
radioGroupChild.addView(button);
}
并且我需要将可绘制按钮设置为 null(我只想在背景上显示文本)。使用 android:button="@null"
在 XML 中手动执行此操作效果很好,但我不想对每个单选按钮进行硬编码。我试过只是做 button.setButtonDrawable(null)
但它没有改变任何东西。
非常感谢任何帮助!
最佳答案
您需要设置一个空的 StateListDrawable
作为可绘制对象。所以 android:button="@null"
的 Java 等价物是:
radioButton.setButtonDrawable(new StateListDrawable());
关于android - 如何以编程方式设置 android :button ="@null"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16284431/