开发者

Android: Change the style of RadioButtons programmatically

开发者 https://www.devze.com 2023-03-11 21:09 出处:网络
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:

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) {
    StateLis开发者_JAVA百科tDrawable 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);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消