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

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

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


当前回答

我刚才的结论是:

覆盖CheckBox并添加此方法,如果你有一个自定义绘制对象:

@Override
public int getCompoundPaddingLeft() {

    // Workarround for version codes < Jelly bean 4.2
    // The system does not apply the same padding. Explantion:
    // http://stackoverflow.com/questions/4037795/android-spacing-between-checkbox-and-text/4038195#4038195

    int compoundPaddingLeft = super.getCompoundPaddingLeft();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Drawable drawable = getResources().getDrawable( YOUR CUSTOM DRAWABLE );
        return compoundPaddingLeft + (drawable != null ? drawable.getIntrinsicWidth() : 0);
    } else {
        return compoundPaddingLeft;
    }

}

或者如果你使用系统绘图:

@Override
public int getCompoundPaddingLeft() {

    // Workarround for version codes < Jelly bean 4.2
    // The system does not apply the same padding. Explantion:
    // http://stackoverflow.com/questions/4037795/android-spacing-between-checkbox-and-text/4038195#4038195

    int compoundPaddingLeft = super.getCompoundPaddingLeft();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return compoundPaddingLeft + (drawable != null ? (int)(10.0f * scale + 0.5f) : 0);
    } else {
        return compoundPaddingLeft;
    }

}

谢谢你的回答:)

其他回答

您需要获取正在使用的图像的大小,以便将填充添加到此大小。在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:衬垫= 5dp

在我的情况下,我解决了这个问题使用以下复选框属性在XML:

*

android: paddingLeft = " @dimen / activity_horizontal_margin”

*

简单的解决方案,在CheckBox属性中添加这一行,用你想要的间距值替换10dp

android:paddingLeft="10dp"

在XML文件中只需要有一个参数

android:paddingLeft="20dp"