Add margin between a RadioButton and its label in Android?

allclaws picture allclaws · Jan 25, 2010 · Viewed 68.6k times · Source

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:

  1. 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.

  2. 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)

  3. 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?

Answer

Jim Baca picture Jim Baca · May 24, 2013

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+.

combine screenshots showing left padding differences between API versions