checkbox android文字间距,Android - Spacing between CheckBox and text

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

bdc6d5a20c830a14ee76f3430909425e.png

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

4d33324a4be6ec33b464133bca815312.png

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.

115e81fb398dfa64d4e3a865bae97248.png

UPDATE - As people have recently mentioned in answers below, this behavior has apparently changed in Jelly Bean (4.2). Your app will need to check which version its running on, and use the appropriate method.

For 4.3+ it is simply setting padding_left. See htafoya's answer for details.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值