Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align checkbox to the right side in LinearLayout android

I am trying to make some text views with checkboxes in LinearLayout. I want for result like this:

TextView           Ckeckbox
TextViewwwwww      Ckeckbox
TextV              Ckeckbox

But currently I have this:

TextView  Checkbox
TextViewwwww  Checkbox
TextView  Checkbox

Here is my xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:orientation="horizontal">

  <TextView
    android:id="@+id/itemTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
 <CheckBox
        android:id="@+id/checkItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</LinearLayout>

And this xml gives me same result:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:orientation="horizontal">

  <TextView
    android:id="@+id/itemTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="start"/>
 <CheckBox
        android:id="@+id/checkItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="end"/>
</LinearLayout>
like image 393
Andrew_Z Avatar asked Jan 29 '26 22:01

Andrew_Z


1 Answers

You can use the layout_weight attribute on your TextView only to automatically designate the TextView to fill any space which the CheckBox does not occupy. For example, the following will set your checkboxes to the end (provided they have no text associated with them) and then lets the TextView fill the rest of the layout.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/itemTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <CheckBox
        android:id="@+id/checkItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Additionally, you should use match_parent instead of fill_parent as fill_parent is deprecated.

like image 126
Joseph Roque Avatar answered Jan 31 '26 12:01

Joseph Roque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!