Как убрать ненужные пробелы справа от CheckBox? - PullRequest
13 голосов
/ 15 июня 2011

Я работаю над настраиваемым представлением списка. Я хочу показать CheckBox в пользовательском представлении. Там нет текста для CheckBox. Я обнаружил, что всегда есть пробелы справа от CheckBox.

Вот мой макет XML-файла:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal" android:background="#fa9654"
android:paddingTop="65dp" android:paddingBottom="65dp">



<TextView android:id="@+id/bus_route_list_item_num"
    android:layout_height="wrap_content" android:layout_width="0dip"
    android:gravity="center" android:layout_gravity="center_vertical|center_horizontal"
    android:layout_weight="0.15"></TextView>

<TextView android:id="@+id/bus_route_list_item_station"
    android:layout_height="wrap_content" android:layout_width="0dip"
    android:gravity="left" android:layout_gravity="center_vertical|center_horizontal"
    android:layout_weight=".5"></TextView>


<TextView android:id="@+id/bus_route_list_item_fee"
    android:layout_height="wrap_content" android:layout_width="0dip"
    android:gravity="center" android:layout_gravity="center_vertical|center_horizontal"
    android:layout_weight=".15"></TextView>


<CheckBox android:id="@+id/bus_route_list_item_reminder" android:layout_height="wrap_content" 
    android:layout_width="0dip" android:layout_weight=".20" android:gravity="center" 
    android:layout_gravity="center" android:paddingRight="0dp" android:paddingLeft="0dp" 
    android:paddingTop="0dp" android:paddingBottom="0dp" android:background="#0066ff" 
    android:text=""
/>

</LinearLayout>

Результат выглядит так:
http://pwong.name/checkbox_problem2.jpg

Как видите, справа от флажка есть место. Я хочу поставить флажок в середине синей области.

Возможно ли удалить ненужное место? спасибо

Ответы [ 5 ]

17 голосов
/ 15 июня 2011

Вы можете обернуть CheckBox в LinearLayout и затем использовать android:gravity="center" в этом макете.

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

В качестве другой альтернативы вы можете использовать RelativeLayout. Это значительно упростит ваш макет, и вы сможете избавиться от layout_weight.

7 голосов
/ 12 июня 2017

Ни одно из предыдущих решений не сработало для меня, но я попытался применить перевод к контенту, и он работал довольно хорошо, нет необходимости в дополнительной иерархии макета или реализации собственных представлений:

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

Кроме того, он удерживает границы элемента в нужном месте, поэтому область касания не смещается.

2 голосов
/ 04 декабря 2013

Чтобы удалить лишний пробел справа от изображения (когда текста нет), расширьте класс CheckBox и переопределите getSuggestedMinimumWidth () метод, чтобы вернуть туда ширину изображения. Комплексное решение:

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);
    }
}
0 голосов
/ 13 января 2019

Кажется, что translationX работает. Но это вызывает проблемы, если вы хотите поддерживать макеты RTL. Другим решением было бы установить ширину флажка на фиксированную длину (например, 26dp):

<CheckBox
    android:layout_width="26dp"
    android:layout_height="wrap_content"
    android:text="@null" />
0 голосов
/ 15 июня 2011

Я бы использовал здесь относительное расположение.Установив флажок на родительском праве ...

С уважением, Стефан

...