Search code examples
androidtextviewandroid-linearlayoutright-align

Right align and center align TextView without layout_width="wrap_content"


I need to right-align a textview, but because I'm using layout_weight, I need to set layout_width="0dip". Setting layout_width="wrap_content" breaks my layout.

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:weightSum="2" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dip"
            android:layout_height="wrap_content"         
            android:layout_weight="0.95"
            android:gravity="center_vertical|right"
            android:text="name" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.1"
            android:gravity="center_vertical|center"
            android:text="=" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.95"
            android:gravity="center_vertical|left"
            android:text="value" />

    </LinearLayout>

The intent is to have a name-value pair aligned to the center of the row, like this: name-value pair

All my searching has only yielded the solution to set layout_width="wrap_content", which won't work here. Any suggestions?


Solution

  • This is your full xml:

    Just update Main LinearLayout with android:layout_width="fill_parent"

    <?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:weightSum="2" >
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.95"
            android:gravity="center_vertical|right"
            android:text="name" />
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.1"
            android:gravity="center_vertical|center"
            android:text="=" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.95"
            android:gravity="center_vertical|left"
            android:text="value" />
    
    </LinearLayout>
    

    Output is:

    enter image description here