How to align CheckBox to the top of its descriptio

2020-06-01 05:47发布

问题:

I would like to align CheckBox "symbol" to the top of its description.

What I have now:

What I want to have:

Current xml:

<CheckBox android:id="@+id/register_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/register_hint"/>

I've tried to achieve this by manipulating layout_gravity attributes, but it doesn't work.

回答1:

android:gravity="top" will fix the problem:

<CheckBox android:id="@+id/register_checkbox"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/register_hint"
          android:gravity="top"/>

Note that android:gravity is different than android:layout_gravity.



回答2:

  • use

    android:gravity="top" it will pin the box on top

  • use

    padding_top="4dp" will adjust Text padding only (without changing box padding from top)



回答3:

I found that:

 android:gravity="fill"

works better than "top". Top wouldn't look right if the checkbox may also end up as only one line.



回答4:

You can try this code:-

    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false">
        <layer-list>
            <item android:top="2dp">
                <bitmap android:gravity="center" android:src="@drawable/checkbox" />
            </item>
        </layer-list>
    </item>
    <item android:state_checked="true">
        <layer-list>
            <item android:top="2dp">
                <bitmap android:gravity="center" android:src="@drawable/checkboxselected" />
            </item>
        </layer-list>
    </item>
    <item>
        <layer-list>
            <item android:top="2dp">
                <bitmap android:gravity="center" android:src="@drawable/checkbox" />
            </item>
        </layer-list>
    </item>
</selector>