Android - 复选框和文本之间的间距

发布于 2024-09-30 00:34:08 字数 158 浏览 3 评论 0 原文

有没有一种简单的方法可以在 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:
alt text

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

羁绊已千年 2024-10-07 00:34:08

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

红线显示整个复选框的 paddingLeft 偏移值

alt text

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

alt text

事实证明,您无法在 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());

这将为您提供以下结果,其中绿线是填充的增加。这比硬编码值更安全,因为不同的设备可以对复选框使用不同的可绘制对象。

alt text

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

对于 4.3+,只需设置 padding_left。详情请参阅 htafoya 的回答。

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

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.

眼波传意 2024-10-07 00:34:08

鉴于@DougW响应,我管理版本的方法更简单,我添加到我的复选框视图中:

android:paddingLeft="@dimen/padding_checkbox"

在两个值文件夹中找到尺寸:

values

<resources>

    <dimen name="padding_checkbox">0dp</dimen>

</resources>

values-v17 (4.2 JellyBean)< /strong>

<resources>

    <dimen name="padding_checkbox">10dp</dimen>

</resources>

我有一个自定义检查,使用dps给你最好的选择。

Given @DougW response, what I do to manage version is simpler, I add to my checkbox view:

android:paddingLeft="@dimen/padding_checkbox"

where the dimen is found in two values folders:

values

<resources>

    <dimen name="padding_checkbox">0dp</dimen>

</resources>

values-v17 (4.2 JellyBean)

<resources>

    <dimen name="padding_checkbox">10dp</dimen>

</resources>

I have a custom check, use the dps to your best choice.

叫嚣ゝ 2024-10-07 00:34:08

使用属性 android:drawableLeft 而不是 android:button。为了设置可绘制对象和文本之间的填充,请使用android:drawablePadding。要定位可绘制对象,请使用android:paddingLeft

<CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@null"
        android:drawableLeft="@drawable/check_selector"
        android:drawablePadding="-50dp"
        android:paddingLeft="40dp"
        />

结果

Use attribute android:drawableLeft instead of android:button. In order to set padding between drawable and text use android:drawablePadding. To position drawable use android:paddingLeft.

<CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@null"
        android:drawableLeft="@drawable/check_selector"
        android:drawablePadding="-50dp"
        android:paddingLeft="40dp"
        />

result

哆兒滾 2024-10-07 00:34:08

Android 4.2 Jelly Bean (API 17) 将文本 paddingLeft 从 ButtonDrawable 中放置(ints 右边缘)。它也适用于 RTL 模式。

在 4.2 之前,paddingLeft 忽略了buttonDrawable - 它是从CompoundButton 视图的左边缘获取的。

您可以通过 XML 来解决它 - 在旧版 Android 上将 paddingLeft 设置为 buttonDrawable.width + requiredSpace。仅在 API 17 及更高版本上将其设置为 requiredSpace。例如,使用维度资源并覆盖 value-v17 资源文件夹。

该更改是通过 android.widget.CompoundButton.getCompoundPaddingLeft() 引入的;

Android 4.2 Jelly Bean (API 17) puts the text paddingLeft from the buttonDrawable (ints right edge). It also works for RTL mode.

Before 4.2 paddingLeft was ignoring the buttonDrawable - it was taken from the left edge of the CompoundButton view.

You can solve it via XML - set paddingLeft to buttonDrawable.width + requiredSpace on older androids. Set it to requiredSpace only on API 17 up. For example use dimension resources and override in values-v17 resource folder.

The change was introduced via android.widget.CompoundButton.getCompoundPaddingLeft();

独留℉清风醉 2024-10-07 00:34:08

是的,您可以通过添加内边距来添加内边距。

android:padding=5dp

Yes, you can add padding by adding padding.

android:padding=5dp

漆黑的白昼 2024-10-07 00:34:08

如果您想要一个没有代码的干净设计,请使用:

<CheckBox
   android:id="@+id/checkBox1"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:drawableLeft="@android:color/transparent"
   android:drawablePadding="10dp"
   android:text="CheckBox"/>

技巧是将 android:drawableLeft 的颜色设置为透明,并为 android:drawablePadding 分配一个值。此外,透明度允许您在任何背景颜色上使用此技术,而不会产生副作用(例如颜色不匹配)。

If you want a clean design without codes, use:

<CheckBox
   android:id="@+id/checkBox1"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:drawableLeft="@android:color/transparent"
   android:drawablePadding="10dp"
   android:text="CheckBox"/>

The trick is to set colour to transparent for android:drawableLeft and assign a value for android:drawablePadding. Also, transparency allows you to use this technique on any background colour without the side effect - like colour mismatch.

赠意 2024-10-07 00:34:08

API 17及以上版本,您可以使用:

android:paddingStart="24dp"

API 16及以下版本,您可以使用:

android:paddingLeft="24dp"

API 17 and above, you can use:

android:paddingStart="24dp"

API 16 and below, you can use:

android:paddingLeft="24dp"

无戏配角 2024-10-07 00:34:08

就我而言,我使用 XML 中的以下 CheckBox 属性解决了这个问题:

*

android:paddingLeft="@dimen/activity_horizo​​ntal_margin"

*

In my case I solved this problem using this following CheckBox attribute in the XML:

*

android:paddingLeft="@dimen/activity_horizontal_margin"

*

━╋う一瞬間旳綻放 2024-10-07 00:34:08

简单的解决方案,在 CheckBox 属性中添加此行,将 10dp 替换为您想要的间距值

android:paddingLeft="10dp"

Simple solution, add this line in the CheckBox properties, replace 10dp with your desired spacing value

android:paddingLeft="10dp"
鼻尖触碰 2024-10-07 00:34:08

我不知道大家,但我测试了

并且仅将文本移动到右侧,而不是整个控件。

它很适合我。

I don't know guys, but I tested

<CheckBox android:paddingLeft="8mm" and only moves the text to the right, not entire control.

It suits me fine.

感情洁癖 2024-10-07 00:34:08

对于复选标记和文本之间的空间使用:

android:paddingLeft="10dp"

但它变得超过10dp,因为复选标记周围包含填充(大约5dp)。如果您想删除内边距,请参阅如何删除 Android CheckBox 周围的内边距

android:paddingLeft="-5dp"
android:layout_marginStart="-5dp"
android:layout_marginLeft="-5dp"
// or android:translationX="-5dp" instead of layout_marginLeft

For space between the check mark and the text use:

android:paddingLeft="10dp"

But it becomes more than 10dp, because the check mark contains padding (about 5dp) around. If you want to remove padding, see How to remove padding around Android CheckBox:

android:paddingLeft="-5dp"
android:layout_marginStart="-5dp"
android:layout_marginLeft="-5dp"
// or android:translationX="-5dp" instead of layout_marginLeft
猫瑾少女 2024-10-07 00:34:08

为什么不直接扩展 Android CheckBox 以获得更好的填充呢?这样,您不必每次使用 CheckBox 时都在代码中修复它,您只需使用固定的 CheckBox 即可。

首先扩展 CheckBox:

package com.whatever;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;

/**
 * This extends the Android CheckBox to add some more padding so the text is not on top of the
 * CheckBox.
 */
public class CheckBoxWithPaddingFix extends CheckBox {

    public CheckBoxWithPaddingFix(Context context) {
        super(context);
    }

    public CheckBoxWithPaddingFix(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CheckBoxWithPaddingFix(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public int getCompoundPaddingLeft() {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (super.getCompoundPaddingLeft() + (int) (10.0f * scale + 0.5f));
    }
}

在 xml 中创建扩展的 CheckBox,而不是创建普通的 CheckBox

<com.whatever.CheckBoxWithPaddingFix
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello there" />

Why not just extend the Android CheckBox to have better padding instead. That way instead of having to fix it in code every time you use the CheckBox you can just use the fixed CheckBox instead.

First Extend CheckBox:

package com.whatever;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;

/**
 * This extends the Android CheckBox to add some more padding so the text is not on top of the
 * CheckBox.
 */
public class CheckBoxWithPaddingFix extends CheckBox {

    public CheckBoxWithPaddingFix(Context context) {
        super(context);
    }

    public CheckBoxWithPaddingFix(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CheckBoxWithPaddingFix(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public int getCompoundPaddingLeft() {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (super.getCompoundPaddingLeft() + (int) (10.0f * scale + 0.5f));
    }
}

Second in your xml instead of creating a normal CheckBox create your extended one

<com.whatever.CheckBoxWithPaddingFix
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello there" />
染年凉城似染瑾 2024-10-07 00:34:08

对于我来说,在 Android 9 API 28 上,将 minHeight 和 minWidth 设置为 0dp 是最干净、最直接的解决方案:

<CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="0dp"
        android:minWidth="0dp" />

Setting minHeight and minWidth to 0dp was the cleanest and directest solution for me on Android 9 API 28:

<CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="0dp"
        android:minWidth="0dp" />
驱逐舰岛风号 2024-10-07 00:34:08

我刚刚得出结论:

如果您有自定义可绘制对象,则覆盖 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;
    }

}

感谢您的回答:)

I just concluded on this:

Override CheckBox and add this method if you have a custom drawable:

@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;
    }

}

or this if you use the system drawable:

@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;
    }

}

Thanks for the answer :)

眼眸里的那抹悲凉 2024-10-07 00:34:08

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

android:paddingLeft="20dp"

only you need to have one parameter in xml file

android:paddingLeft="20dp"
花伊自在美 2024-10-07 00:34:08

这种行为在 Jelly Bean 中似乎有所改变。 paddingLeft 技巧添加了额外的填充,使文本看起来太靠右。还有人注意到这一点吗?

This behavior appears to have changed in Jelly Bean. The paddingLeft trick adds additional padding, making the text look too far right. Any one else notice that?

时光暖心i 2024-10-07 00:34:08

如果有人需要在可绘制对象周围填充试试这个

        <com.google.android.material.checkbox.MaterialCheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@null"
        android:drawableStart="@drawable/button_selector"
        android:padding="@dimen/items_padding" />

if some one need padding around drawable try this

        <com.google.android.material.checkbox.MaterialCheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@null"
        android:drawableStart="@drawable/button_selector"
        android:padding="@dimen/items_padding" />
述情 2024-10-07 00:34:08
<CheckBox
        android:paddingRight="12dip" />
<CheckBox
        android:paddingRight="12dip" />
后来的我们 2024-10-07 00:34:08

如果您有复选框或单选按钮的自定义图像选择器,则必须设置相同的按钮和背景属性,如下所示:

            <CheckBox
                android:id="@+id/filter_checkbox_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:button="@drawable/selector_checkbox_filter"
                android:background="@drawable/selector_checkbox_filter" />

您可以使用背景属性控制复选框或单选按钮填充的大小。

If you have custom image selector for checkbox or radiobutton you must set same button and background property such as this:

            <CheckBox
                android:id="@+id/filter_checkbox_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:button="@drawable/selector_checkbox_filter"
                android:background="@drawable/selector_checkbox_filter" />

You can control size of checkbox or radio button padding with background property.

时光瘦了 2024-10-07 00:34:08

我认为这可以帮助你

<CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawablePadding="-30dp"
        android:paddingLeft="30dp"
        android:drawableLeft="@drawable/check"
        />

I think this can help you

<CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawablePadding="-30dp"
        android:paddingLeft="30dp"
        android:drawableLeft="@drawable/check"
        />

二智少女 2024-10-07 00:34:08

如果您要创建自定义按钮,例如请参阅 更改复选框外观教程

然后只需增加宽度btn_check_label_background.9.png 通过在图像中心添加一列或两列透明像素来实现;保留 9 块标记不变。

If you are creating custom buttons, e.g. see change look of checkbox tutorial

Then simply increase the width of btn_check_label_background.9.png by adding one or two more columns of transparent pixels in the center of the image; leave the 9-patch markers as they are.

飘逸的'云 2024-10-07 00:34:08

我所做的是在(相对)Layout 内有一个 TextView 和一个 CheckBoxTextView 显示我希望用户看到的文本,而 CheckBox 没有任何文本。这样,我就可以在任意位置设置 CheckBox 的位置/填充。

What I did, is having a TextView and a CheckBox inside a (Relative)Layout. The TextView displays the text that I want the user to see, and the CheckBox doesn't have any text. That way, I can set the position / padding of the CheckBox wherever I want.

于我来说 2024-10-07 00:34:08

我在 Galaxy S3 mini (android 4.1.2) 上遇到了同样的问题,我只是简单地扩展了我的自定义复选框 AppCompatCheckBox 而不是 CheckBox。现在它工作得很好。

I had the same problem with a Galaxy S3 mini (android 4.1.2) and I simply made my custom checkbox extend AppCompatCheckBox instead of CheckBox. Now it works perfectly.

绳情 2024-10-07 00:34:08

@CoolMind 有很好的方法,但它无法通过 android:paddingLeft 在复选框开头添加空格,而是使用这种方式

<androidx.appcompat.widget.AppCompatCheckBox
                android:id="@+id/cbReason5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/white"
                android:button="@null"
                android:drawableStart="@drawable/custom_bg_checkbox"
                android:drawablePadding="8dp"
                android:paddingStart="16dp"
                android:paddingTop="12dp"
                android:paddingEnd="16dp"
                android:paddingBottom="12dp"
                android:text="Whatever"
                android:textColor="@color/textNormal"
                app:buttonCompat="@null" />

android:drawablePadding 应该可以帮助你

@CoolMind has the nice way but it couldn't add the space at the beginning of checkbox by android:paddingLeft, instead use this way

<androidx.appcompat.widget.AppCompatCheckBox
                android:id="@+id/cbReason5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/white"
                android:button="@null"
                android:drawableStart="@drawable/custom_bg_checkbox"
                android:drawablePadding="8dp"
                android:paddingStart="16dp"
                android:paddingTop="12dp"
                android:paddingEnd="16dp"
                android:paddingBottom="12dp"
                android:text="Whatever"
                android:textColor="@color/textNormal"
                app:buttonCompat="@null" />

android:drawablePadding should help you

在梵高的星空下 2024-10-07 00:34:08

您需要获取正在使用的图像的大小,以便将填充添加到该大小。在 Android 内部,他们获取您在 src 上指定的可绘制对象,然后使用其大小。因为它是一个私有变量并且没有 getter,所以你无法访问它。此外,您无法获取 com.android.internal.R.styleable.CompoundButton 并从那里获取可绘制对象。

因此,您需要创建自己的样式(即 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;
    }
}

You need to get the size of the image that you are using in order to add your padding to this size. On the Android internals, they get the drawable you specify on src and use its size afterwards. Since it's a private variable and there are no getters you cannot access to it. Also you cannot get the com.android.internal.R.styleable.CompoundButton and get the drawable from there.

So you need to create your own styleable (i.e. custom_src) or you can add it directly in your implementation of the 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;
    }
}
安稳善良 2024-10-07 00:34:08

由于您可能为 android:button 属性使用可绘制选择器,因此您需要添加 android:constantSize="true" 和/或指定一个默认可绘制,如下所示

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:constantSize="true">
  <item android:drawable="@drawable/check_on" android:state_checked="true"/>
  <item android:drawable="@drawable/check_off"/>
</selector>

:您需要在复选框 xml 中指定 android:paddingLeft 属性。

缺点:

在布局编辑器中,您将在 api 16 及以下版本的复选框下显示文本,在这种情况下,您可以通过创建自定义复选框类来修复它,例如 建议,但适用于 api 级别 16。

理由:

这是一个错误,因为 StateListDrawable#getIntrinsicWidth() 调用是在 CompoundButton 内部使用,但它可能返回 <如果没有当前状态且未使用常量大小,则为 0 值。

As you probably use a drawable selector for your android:button property you need to add android:constantSize="true" and/or specify a default drawable like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:constantSize="true">
  <item android:drawable="@drawable/check_on" android:state_checked="true"/>
  <item android:drawable="@drawable/check_off"/>
</selector>

After that you need to specify android:paddingLeft attribute in your checkbox xml.

Cons:

In the layout editor you will the text going under the checkbox with api 16 and below, in that case you can fix it by creating you custom checkbox class like suggested but for api level 16.

Rationale:

it is a bug as StateListDrawable#getIntrinsicWidth() call is used internally in CompoundButton but it may return < 0 value if there is no current state and no constant size is used.

也只是曾经 2024-10-07 00:34:08

要解决这个问题,您所要做的就是将 android:singleLine="true" 添加到 android xml 布局中的 checkBox 中:

<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"/>

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

All you have to do to overcome this problem is to add android:singleLine="true" to the checkBox in your android xml layout:

<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"/>

and nothing special will be added programmatically.

弥枳 2024-10-07 00:34:08

当我使用选择器中的自己的可绘制对象时,复选框图像重叠,我已使用以下代码解决了此问题:

CheckBox cb = new CheckBox(mActivity);
cb.setText("Hi");
cb.setButtonDrawable(R.drawable.check_box_selector);
cb.setChecked(true);
cb.setPadding(cb.getPaddingLeft(), padding, padding, padding);

感谢 Alex Semeniuk

Checkbox image was overlapping when I used my own drawables from selector, I have solve this using below code :

CheckBox cb = new CheckBox(mActivity);
cb.setText("Hi");
cb.setButtonDrawable(R.drawable.check_box_selector);
cb.setChecked(true);
cb.setPadding(cb.getPaddingLeft(), padding, padding, padding);

Thanks to Alex Semeniuk

乱世争霸 2024-10-07 00:34:08

我通过更改图像最终解决了这个问题。
刚刚在 png 文件中添加了额外的透明背景。
该解决方案在所有 API 上都表现出色。

I end up with this issue by changing the images.
Just added extra transparent background in png files.
This solution works excellent on all the APIs.

生生漫 2024-10-07 00:34:08

也许为时已晚,但我已经创建了实用方法来管理这个问题。

只需将此方法添加到您的实用程序中:

public static void setCheckBoxOffset(@NonNull  CheckBox checkBox, @DimenRes int offsetRes) {
    float offset = checkBox.getResources().getDimension(offsetRes);
    setCheckBoxOffsetPx(checkBox, offset);
}

public static void setCheckBoxOffsetPx(@NonNull CheckBox checkBox, float offsetInPx) {
    int leftPadding;
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
        leftPadding = checkBox.getPaddingLeft() + (int) (offsetInPx + 0.5f);
    } else {
        leftPadding = (int) (offsetInPx + 0.5f);
    }
    checkBox.setPadding(leftPadding,
            checkBox.getPaddingTop(),
            checkBox.getPaddingRight(),
            checkBox.getPaddingBottom());
}

并像这样使用:

    ViewUtils.setCheckBoxOffset(mAgreeTerms, R.dimen.space_medium);

或像这样:

    // Be careful with this usage, because it sets padding in pixels, not in dp!
    ViewUtils.setCheckBoxOffsetPx(mAgreeTerms, 100f);

Maybe it is to late, but I've created utility methods to manage this issue.

Just add this methods to your utils:

public static void setCheckBoxOffset(@NonNull  CheckBox checkBox, @DimenRes int offsetRes) {
    float offset = checkBox.getResources().getDimension(offsetRes);
    setCheckBoxOffsetPx(checkBox, offset);
}

public static void setCheckBoxOffsetPx(@NonNull CheckBox checkBox, float offsetInPx) {
    int leftPadding;
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
        leftPadding = checkBox.getPaddingLeft() + (int) (offsetInPx + 0.5f);
    } else {
        leftPadding = (int) (offsetInPx + 0.5f);
    }
    checkBox.setPadding(leftPadding,
            checkBox.getPaddingTop(),
            checkBox.getPaddingRight(),
            checkBox.getPaddingBottom());
}

And use like this:

    ViewUtils.setCheckBoxOffset(mAgreeTerms, R.dimen.space_medium);

or like this:

    // Be careful with this usage, because it sets padding in pixels, not in dp!
    ViewUtils.setCheckBoxOffsetPx(mAgreeTerms, 100f);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文