【问题标题】:How can I programmatically set android:button="@null"?如何以编程方式设置 android:button="@null"?
【发布时间】:2013-04-23 11:03:26
【问题描述】:

我正在尝试以编程方式将一组 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),但它并没有改变任何东西。

非常感谢任何帮助!

【问题讨论】:

标签: android android-layout radio-button


【解决方案1】:

你应该这样做:

button.setBackgroundDrawable(null);

如果你的drawable引用了选择器,你可以通过你的选择器xml使其透明:

<item android:drawable="@android:color/transparent" />

你可能已经找到了解决方案;)

【讨论】:

  • 我上面说了,我试过了,但由于某种原因它不起作用。
  • 它是 setBackgroundDrawable,而不是 setButtonDrawable。
  • 哦,抱歉,没看到。问题是,这只是删除了我设置自定义选择器可绘制的背景。
  • 好的,那么你应该在你的选择器xml中设置一个透明的颜色。
  • 从 API 16 开始,setBackgroundDrawable 已弃用。在这种情况下请改用setBackground(null)
【解决方案2】:

你需要设置一个空的StateListDrawable 作为drawable。所以android:button="@null"的Java等价物是:

radioButton.setButtonDrawable(new StateListDrawable());

【讨论】:

  • 这对我来说非常有效。不知道为什么它不是最佳答案。
  • 也为我工作!谢谢!
  • 这和 setButtonDrawable(android.R.color.transparent); 一样
  • 并非在所有设备上,为什么?没有在 hTC one X 上工作,在 Nexus 4 上工作。
  • 这比设置为答案的答案更好!谢谢
【解决方案3】:

setButtonDrawable(getResources().getDrawable(android.R.color.transparent)) 应该做的伎俩。

只有这对我有用。

【讨论】:

  • 您可以像@amalan 在之前的评论中指出的那样简单地输入setButtonDrawable(android.R.color.transparent);
【解决方案4】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多