Android - CheckBox 和文本之间的间距 [英] Android - Spacing between CheckBox and text

查看:22
本文介绍了Android - CheckBox 和文本之间的间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以在 CheckBox 控件中的复选框和相关文本之间添加填充?

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:

推荐答案

我不想回答我自己的问题,但在这种情况下,我认为我需要回答.检查出来后,@Falmarri 的回答是正确的.问题是 Android 的 CheckBox 控件已经使用 android:paddingLeft 属性来获取文本所在的位置.

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.

红线表示整个CheckBox的paddingLeft偏移值

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

如果我只是在我的 XML 布局中覆盖该填充,它会弄乱布局.以下是设置 paddingLeft="0" 的作用:

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

事实证明您无法在 XML 中修复此问题.你已经在代码中做到了.这是我的代码片段,硬编码填充增加了 10dp.

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.

更新 - 正如人们最近在下面的答案中提到的那样,这种行为在 Jelly Bean (4.2) 中显然发生了变化.您的应用需要检查其运行的版本,并使用适当的方法.

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.

对于 4.3+,它只是设置 padding_left.详情见 htafoya 的回答.

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

这篇关于Android - CheckBox 和文本之间的间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆