是否有一种简单的方法可以在复选框控件中的复选框和相关文本之间添加填充?
我不能只添加前导空格,因为我的标签是多行。
就像,文本太接近复选框了:
是否有一种简单的方法可以在复选框控件中的复选框和相关文本之间添加填充?
我不能只添加前导空格,因为我的标签是多行。
就像,文本太接近复选框了:
当前回答
也许已经太晚了,但是我已经创建了实用工具方法来管理这个问题。
只需将这些方法添加到您的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());
}
像这样使用:
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);
其他回答
我有同样的问题与Galaxy S3 mini (android 4.1.2),我只是让我的自定义复选框扩展AppCompatCheckBox而不是checkbox。现在它工作得很完美。
为什么不扩展Android复选框以获得更好的填充呢?这样一来,每次使用复选框时都不必在代码中修复它,而只需使用固定的复选框即可。
第一个扩展复选框:
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中创建一个扩展的复选框,而不是创建一个普通的复选框
<com.whatever.CheckBoxWithPaddingFix
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello there" />
如果你想要一个没有代码的干净的设计,使用:
<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: drawablleft设置颜色为透明,并为android:drawablePadding赋值。此外,透明度允许你在任何背景颜色上使用这种技术,而不会产生类似颜色不匹配的副作用。
在我的情况下,我解决了这个问题使用以下复选框属性在XML:
*
android: paddingLeft = " @dimen / activity_horizontal_margin”
*
如果你有自定义图像选择框或单选按钮,你必须设置相同的按钮和背景属性,如下所示:
<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" />
您可以用背景属性控制复选框或单选按钮填充的大小。