How to remove unwanted spaces at the right of CheckBox?

时光怂恿深爱的人放手 提交于 2019-12-04 00:23:38

You can wrap CheckBox in LinearLayout and then use android:gravity="center" on that layout.

 <LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="0dip" 
    android:layout_weight=".20"              
    android:background="#ff0000" 
    android:gravity="center">

    <CheckBox android:id="@+id/bus_route_list_item_reminder" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"                     
    />

</LinearLayout>

As another alternative, you can use RelativeLayout. This would greatly simplify you layout and you will be able to get rid of layout_weight.

Neither of previous solutions worked for me, but I've tried applying a translation to the content and it worked pretty well, no need in additional layout hierarchy, nor implementing own views:

                <CheckBox
                ...
                android:text="@null"
                android:translationX="12dp" />

Also, it keeps bounds of the element in proper place, so touch area is not shifted.

To remove extra space at right of the image (when there is no text) extend CheckBox class and override getSuggestedMinimumWidth() method in order to return there image width. Complete solution:

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.CheckBox;

public class CheckBoxWithoutText extends CheckBox
{
    private Drawable buttonDrawable;

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

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

    @Override
    protected int getSuggestedMinimumWidth()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
        {
            return getCompoundPaddingLeft() + getCompoundPaddingRight();
        }
        else
        {
            return buttonDrawable == null ? 0 : buttonDrawable.getIntrinsicWidth();
        }
    }

    @Override
    public void setButtonDrawable(Drawable d)
    {
        buttonDrawable = d;
        super.setButtonDrawable(d);
    }
}

I would use a relative layout here. Aligning checkbox on parent right...

Regards, Stéphane

The translationX seems to work. But it causes problem if you want to support RTL layouts. Another solution would be to set the width of checkbox to a fixed length (e.g. 26dp):

<CheckBox
    android:layout_width="26dp"
    android:layout_height="wrap_content"
    android:text="@null" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!