Is it possible to add a little bit of space between a RadioButton and the label while still using Android's built-in components? By default the text looks a little scrunched.
<RadioButton android:id="@+id/rb1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="My Text"/>
I've tried a couple of things:
Specifying margin and padding seem to add space around the entire element (button and text, together). That makes sense, but doesn't do what I need.
Creating a custom drawable via XML specifying images for the checked and unchecked states, then adding a few extra pixels to the right side of each image. This should work, but now you are stepping outside the default UI. (Not the end of the world, but not ideal)
Add extra whitespace to the beginning of each label. Android seems to trim a leading space character, as in " My String", but specifying unicode U+00A0, as in "\u00A0My String" does the trick. This works, but it seems kinda dirty.
Any better solutions?
Try using the layout_margin attribute, it works similarly to padding, but may have the effect you want. You can use simply android:layout_margin="20dp" or you can set individual sides, like you can for padding (ex: android:layout_marginLeft="20dp").
To get the selected radio button, we have used radioGroup. getCheckedRadioButtonId() method, which returns the id of the selected radio button. Then to get the text of the selected radio button, we have used getText() method on that selected radio button.
here you go. Use getCheckedRadioButtonId() method on your RadioGroup to find out. It returns -1 when no RadioButton in the group is selected. You are already doing this.
For anyone reading this now, the accepted answer will lead to some layout problems on newer APIs causing too much padding.
On API <= 16 you can set paddingLeft
on the radio button to set the padding relative to the radio button's view bounds. Additionally, a patch nine background also changes the view bounds relative to the view.
On API >= 17 the paddingLeft
(or paddingStart
) is in relation to the radio button drawable. Same applies to the about a patch nine. To better illustrate padding differences see the attached screenshot.
If you dig through the code you will find a new method in API 17 called getHorizontalOffsetForDrawables. This method is called when calculating the left padding for a radio button(hence the additional space illustrated in the picture).
TL;DR Just use paddingLeft
if your minSdkVersion
is >= 17. If you support API <= 16, you should have radio button style for the min SDK you are supporting and another style for API 17+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With