0

所以我在运行时动态创建单选按钮,但我想更改按钮的背景。我在我的 drawables 文件夹中创建了一个选择器 xml 文件,如下所示:

<item android:drawable="@drawable/btn_radio_on_holo_light" android:state_checked="true" android:state_enabled="true" android:state_window_focused="false"/>
<item android:drawable="@drawable/btn_radio_off_holo_light" android:state_checked="false" android:state_enabled="true" android:state_window_focused="false"/>
<item android:drawable="@drawable/btn_radio_on_pressed_holo_light" android:state_checked="true" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_radio_off_pressed_holo_light" android:state_checked="false" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_radio_on_focused_holo_light" android:state_checked="true" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/btn_radio_off_focused_holo_light" android:state_checked="false" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/btn_radio_off_holo_light" android:state_checked="false" android:state_enabled="true"/>
<item android:drawable="@drawable/btn_radio_on_holo_light" android:state_checked="true" android:state_enabled="true"/>
<!-- Disabled states -->
<item android:drawable="@drawable/btn_radio_on_disabled_holo_light" android:state_checked="true" android:state_window_focused="false"/>
<item android:drawable="@drawable/btn_radio_off_disabled_holo_light" android:state_checked="false" android:state_window_focused="false"/>
<item android:drawable="@drawable/btn_radio_on_disabled_focused_holo_light" android:state_checked="true" android:state_focused="true"/>
<item android:drawable="@drawable/btn_radio_off_disabled_focused_holo_light" android:state_checked="false" android:state_focused="true"/>
<item android:drawable="@drawable/btn_radio_off_disabled_holo_light" android:state_checked="false"/>
<item android:drawable="@drawable/btn_radio_on_disabled_holo_light" android:state_checked="true"/>

有谁知道使用这个drawable在运行时更新单选按钮的java代码?谢谢!

4

2 回答 2

-1

试试这个例子:

    StateListDrawable mState1 = new StateListDrawable();
mState1.addState(new int[] { android.R.attr.state_pressed },
    getResources().getDrawable(R.drawable.button3_pressed));
mState1.addState(new int[] { android.R.attr.state_focused },
    getResources().getDrawable(R.drawable.button3_focused));
mState1.addState(new int[] {},
    getResources().getDrawable(R.drawable.button3_up));
myButton.setBackgroundDrawable(mState1);
于 2013-08-05T12:50:01.003 回答