user2260040 user2260040 - 4 months ago 13
Android Question

Android : Align textviews in a listview

I have a listvew which has three textviews. I am not sure how to align them so that the output looks like:

abcded -> xxxx aaa
ddd -> qqq bbb
alkdladd -> hzhdl ccc


Rather than what I am currently getting:

abcded -> xxxx aaa
ddd -> qqq bbb
alkdladd -> hzhdl ccc


The textviews in first row are :

textview1 = abcded
textview2 = -> xxxx
textview3 = aaa


The problem is with the alignment of textview in the middle. How can I go about doing it?

Answer

One option you have is to simply have your list item layout contain a LinearLayout and use weights. Something like:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="6" >

    <TextView
        android:id="@+id/left_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:singleLine="true"
        android:maxLines="1"
        android:ellipsize="end"> />

    <TextView
        android:id="@+id/center_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="4"
        android:singleLine="true"
        android:maxLines="1"
        android:ellipsize="end" />

    <TextView
        android:id="@+id/right_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:singleLine="true"
        android:maxLines="1"
        android:ellipsize ="end" />
</LinearLayout>

This makes the assumption that you only want your text in each view to be a single line. It will ellipsize (add three dots to the end) of any Strings that would otherwise wrap to another line. You can mess with the weights as you need to to get the look you want.

There may be other ways using something like RelativeLayouts or something, but weights (I have found) are the best way to guarantee alignment in your apps universally.