我正在以编程方式将问题的多个答案添加为放射组中的单选按钮(请参见下面的代码和图像)。
我几乎做到了,但我不想有一个单选按钮的一侧有一个文本(见下图),我只想有文本和背景。
我能把单选按钮去掉吗?
或者,我可以将当前背景设置为单选按钮(带有选中/未选中状态),并添加与之重叠的文本吗?
RadioGroup answer_container = (RadioGroup) findViewById(R.id.answer_container);
while (c.isAfterLast() == false) {
RadioButton answer = new RadioButton(PCItem.this);
answer.setText(c.getString(c.getColumnIndex(DBAdapter.KEY_ANS_TEXT)));
answer.setBackgroundResource(R.drawable.btn_ans);
answer.setPadding((int)(30 * density), 0, 0, 0);
answer.setGravity(Gravity.CENTER_VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int)(775 * density), (int)(81 * density));
params.setMargins(0, (int)(20*density), 0, 0);
answer.setLayoutParams(params);
answer_container.addView(answer);
c.moveToNext();
}
最佳答案
您可以使用radioButton.setButtonDrawable()
。还可以使用checked
为每个按钮状态(包括unchecked
/StateListDrawable
)指定不同的绘图项。
要完全删除按钮,只需将其设置为null
:
<RadioButton
android:button="@null"
...
/>
注意,代码
radioButton.setButtonDrawable(null);
不起作用!正确的方法是设置一个空的StateListDrawable
:radioButton.setButtonDrawable(new StateListDrawable());
如果有更多项,可以创建自定义样式来覆盖
RadioButton
的默认属性:<style name="CustomRadioButton" parent="@android:style/Widget.CompoundButton.RadioButton">
<item name="android:button">@null</item>
<item name="android:paddingLeft">0dp</item>
</style>