Diffy
Diffy

Reputation: 2359

Alignment in TableLayout in Android

I want to align two elements at left and right end of my TableRow(pic attached ). In the code shown below, when i write android:layout_column="2", nothing happens. But when i add android:stretchColumns="1" in TableLayout, it works and the elements get aligned as i want. Though i understand the purpose of strechColumns and layout_column, i don't understand why this combination works and why not android:layout_column?

<TableLayout
    android:id="@+id/about_speed"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1">         
    <TableRow>
       <TextView
         android:id="@+id/speed"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Current speed"/>

       <ImageView
         android:id="@+id/speed_help"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:background="@drawable/help_speed"
         android:layout_column="2"/>

    </TableRow>

enter image description here

Upvotes: 0

Views: 129

Answers (2)

MilapTank
MilapTank

Reputation: 10076

may be use of TableLayout is your requirement but this is my suggestion you can achieve same layout in TextView only

<TextView android:id="@+id/speed"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:drawableLeft="@drawable/help_speed"
  android:text="Current speed"/> 

and reduce your layout hierarchy

Upvotes: 1

Giru Bhai
Giru Bhai

Reputation: 14408

You can choose which column to put your widget by using android:layout_column property, you define the Zero-based index of the column where you want your widget to be.

Note: if you specify an index greater than the actual cells count, the widget won’t appear.

In table layout each column occupies space equal to the size of the largest widget in it. But you can set the width of any column to take the largest available space, just like setting the width to 100 % in HTML. This is done by setting the property android:stretchColumns to the index of the column. For more info see at Android Table Layout

And in your case
you set android:stretchColumns="1"—The second column (because the column numbers are 0-based) is stretched to take up any available space in the row.
And android:layout_column="2" means your image will at columns position 2(note:Zero based index).

Therefore when you use android:stretchColumns with android:layout_column,it set image to column position 2 and you stretching column number 1 (android:stretchColumns="1").
Finally in your design text is at 0th position,Stretching 1st column(white space) and setting image at 2nd position.

Upvotes: 1

Related Questions