android - 如何以编程方式设置 android :button ="@null"?

标签 android android-layout radio-button

我正在尝试以编程方式将一组 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/

相关文章:

java - 我怎样才能知道在Android studio中选择了哪个单选按钮

javascript - jQuery 选择器中的括号

Android Wifi 硬件模块

android - GIF 不显示在 Samsung Galaxy Note 2 上

php - 添加单选按钮到 MySQL 获取结果并使用结果值获取另一条记录...?

android - 下面这个View,是用一个还是两个RecyclerView比较好?

android - 相对布局 : Can't assign a view above a referenced view if margin is involved

java - 在 Android 中使用 AppCompatActivity

android - 仅使用 broadcastreceiver 没有 Activity 的电池状态

android - 从内容中获取资源id ://settings/system/ringtone?