How to align CheckBox to the top of its description in Android

允我心安 提交于 2019-12-09 08:21:34

问题


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>


来源:https://stackoverflow.com/questions/34660323/how-to-align-checkbox-to-the-top-of-its-description-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!