【问题标题】:How can I make a RadioButton with overlapping text?如何制作带有重叠文本的 RadioButton?
【发布时间】:2012-01-18 13:15:24
【问题描述】:

我正在以编程方式将问题的多个答案添加为 RadioGroup 中的 RadioButtons(请参见下面的代码和图片)。

我几乎实现了它,但我不想有一个带有文本的单选按钮(见下图),我希望只有文本和背景。

我可以去掉单选按钮吗?

或者我可以将我当前的背景设置为单选按钮(具有选中/未选中状态),并添加一个与其重叠的文本吗?

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();
}

【问题讨论】:

  • 即使我发现同样的问题你能帮帮我吗?

标签: android radio-button


【解决方案1】:

您可以使用radioButton.setButtonDrawable()。您还可以使用StateListDrawable 为每个按钮状态(包括checked/unchecked)指定不同的drawable。

要完全删除按钮,您只需将其设置为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>

【讨论】:

  • 这将设置单选按钮。我想删除它,或者让文本与它重叠。
  • 我尝试以编程方式将按钮设置为 null (answer.setButtonDrawable(null)),但它仍然显示...
【解决方案2】:

好的,我是用的

answer.setButtonDrawable(android.R.color.transparent);

移除按钮,并使用选择器作为 btn_ans:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_checked="false" android:drawable="@drawable/btn_choix_unsel" /> 
<item android:state_checked="true" android:drawable="@drawable/btn_choix_sel" />
</selector>

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2022-01-18
    相关资源
    最近更新 更多