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

我不能只添加前导空格,因为我的标签是多行。

就像,文本太接近复选框了:


当前回答

<CheckBox android:drawablePadding="16dip" -可绘制对象和文本之间的填充。

其他回答

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

红线显示了整个CheckBox的paddingLeft偏移值

如果我重写XML布局中的填充,它就会把布局弄乱。下面是设置paddingLeft="0"的作用:

事实证明,在XML中无法解决这个问题。你必须用代码来做。下面是我的片段,硬编码填充增加10dp。

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

这将得到以下结果,其中绿线是填充的增加。这比硬编码一个值更安全,因为不同的设备可以为复选框使用不同的绘图。

更新-正如人们最近在下面的回答中提到的,这种行为在果冻豆(4.2)中明显发生了变化。你的应用需要检查它运行在哪个版本上,并使用适当的方法。

对于4.3+,它只是设置padding_left。详情请看htafoya的回答。

您需要获取正在使用的图像的大小,以便将填充添加到此大小。在Android内部,它们获取你在src上指定的drawable,然后使用它的大小。因为它是一个私有变量,没有getter,你不能访问它。同样,你也不能得到com.android.internal.R.styleable.CompoundButton并从那里得到drawable。

所以你需要创建你自己的可样式(即custom_src),或者你可以直接在你的RadioButton的实现中添加它:

public class CustomRadioButton extends RadioButton {

    private Drawable mButtonDrawable = null;

    public CustomRadioButton(Context context) {
        this(context, null);
    }

    public CustomRadioButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomRadioButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mButtonDrawable = context.getResources().getDrawable(R.drawable.rbtn_green);
        setButtonDrawable(mButtonDrawable);
    }

    @Override
    public int getCompoundPaddingLeft() {
        if (Util.getAPILevel() <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (drawable != null) {
                paddingLeft += drawable.getIntrinsicWidth();
            }
        }
        return paddingLeft;
    }
}

你所要做的就是在你的android xml布局的复选框中添加android:singleLine="true":

<CheckBox 
   android:id="@+id/your_check_box"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:singleLine="true"
   android:background="@android:color/transparent"
   android:text="@string/your_string"/>

并且不会以编程方式添加任何特殊内容。

<CheckBox android:drawablePadding="16dip" -可绘制对象和文本之间的填充。

我通过改变图像来解决这个问题。 刚刚在png文件中添加了额外的透明背景。 这个解决方案在所有api上都非常有效。