Search code examples
androidandroid-layoutradio-button

How can I programmatically set android:button="@null"?


I'm trying to programmatically add a set of RadioButtons to a RadioGroup like so:

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

and I need to set the button drawable to null (I want just text on top of my background). Manually doing this in the XML with android:button="@null" works great, but I don't want to hardcode each radio button. I've tried just doing button.setButtonDrawable(null) but it doesn't change anything.

Any help is greatly appreciated!


Solution

  • You should do this:

    button.setBackgroundDrawable(null);
    

    If your drawable has a reference to selector you can make it transparent through your selector xml:

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

    as you'd probably found the solution ;)