Maria
Maria

Reputation: 89

Android: Change the style of RadioButtons programmatically

how can I change the background image of RadioButtons in selected state. I have used the code for checkBoxes and it works, but for RadioButtons doesnt work. Here is my code snippet:

RadioGroup radioGroup = new RadioGroup(context);
for ( int i = 0; i < lst.size(); i++ ){
    // Radiobuttons 
    RadioButton radioButton = new RadioButton(context);
    radioButton.setId(i);
    radioButton.setButtonDrawable(myDrawable);
    radioButton.setText(myTxt);
    radioGroup.addView(radioButton, i, layoutParams);

}

this.addView(radioGroup); 

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
    StateListDrawable myStates = new StateListDrawable();
    int stateSelected = android.R.attr.state_selected;
    myStates.addState(new int[]{ -stateSelected }, myDrawable2);

    RadioButton  r = (RadioButton) group.getChildAt(checkedId);
    r.setButtonDrawable(myStates);
}

Upvotes: 0

Views: 5469

Answers (1)

Mark Allison
Mark Allison

Reputation: 21909

You can use a state-list drawable which defines different background images depending on the state of the widget. You can do this instead of changing the background resource programatically.

A tutorial on this can be found here.

Upvotes: 1

Related Questions