Is there a pure-java way of setting the android:button attribute? My use case is I have some radio buttons with custom on/off images. They are currently in xml, but for several reasons I want their creation to be done in pure java. Currently the android:button references a <selector> xml file:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/red_down_full" />
<item android:drawable="@drawable/red_down" />
</selector>
Is there any way to either
- reference the
<selector>xml file in java - skip the
<selector>entirely and just set thestate_checkedimage in java?
Yes, you can set the xml image selector via code. If you want to set the selector on your
RadioButtonyou have to call itssetButtonDrawable(idOfYourSelector).The code will be like this:
If you want to set only the image you used for
state_checked, then you need to supply the id of yourstate_checkedimage onsetButtonDrawable(idOfYourImage)instead the id of your selector. In your case it will be:To ensure that it will not overlap the label of your
RadioButton, you have to know the width of yourdrawable. Then set the left padding of yourRadioButtondepending on the width of yourdrawable. This will ensure the image for yourRadioButtonwill not overlap its label.