views:

58

answers:

3

Is there an easy way to add padding between the checkbox in a CheckBox control, and the associated text?

I cannot just add leading spaces, because my label is multi-line.

As-is, the text is way too close to the checkbox: alt text

+2  A: 

Yes, you can add padding by adding padding.

android:padding=5dp

Falmarri
@Falmarri - This actually works... sort of. For one, only paddingLeft is needed, not all padding. However, it looks like the paddingLeft is already set to a value of around 40dp. If I set it > 40dp it moves away, if I set it < 40dp it moves under the checkbox. I'm going to mark this as correct and open another question, because I have concerns about that.
DougW
Well I have no idea without seeing your layout.
Falmarri
+3  A: 
<CheckBox
        android:paddingRight="12dip" />
AndrewKS
@AndrewKS - Tested. As expected, this adds padding to the entire control, not in between the checkbox and the text.
DougW
You are probably better off having the text in a separate TextView.
AndrewKS
@AndrewKS - Bad idea for usability. I want the user to be able to touch the text and select/deselect the checkbox. It also breaks many accessibility features, the same way as if you do that in a web page.
DougW
`Bad idea for usability` No it's not. Put both the checkbox and the textview in a linear layout and make that linearlayout touchable.
Falmarri
@Falmarri - I mean yeah, I could do that, but then I'm basically re-implementing my own checkbox control. I'd just rather not do that.
DougW
+2  A: 

I hate to answer my own question, but in this case I think I need to. After checking it out, @Falmarri was on the right track with his answer. The problem is that Android's CheckBox control already uses the android:paddingLeft property to get the text where it is.

The red line shows the paddingLeft offset value of the entire CheckBox

alt text

If I just override that padding in my XML layout, it messes up the layout. Here's what setting paddingLeft="0" does:

alt text

Turns out you can't fix this in XML. You have do it in code. Here's my snippet with a hardcoded padding increase of 10dp.

final float scale = this.getResources().getDisplayMetrics().density;
checkBox.setPadding(checkBox.getPaddingLeft() + (int)(10.0f * scale + 0.5f),
        checkBox.getPaddingTop(),
        checkBox.getPaddingRight(),
        checkBox.getPaddingBottom());

This gives you the following, where the green line is the increase in padding. This is safer than hardcoding a value, since different devices could use different drawables for the checkbox.

alt text

DougW
Nothing wrong with answering your own question - someone else will probably have this problem in the future and you just gave a good, comprehensive answer.
AndrewKS