Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Table layout? Two EQUAL-width rows filled with equally width buttons?

Here's a part from my XML for LAND format:

<TableLayout     android:layout_height="wrap_content"     android:layout_width="wrap_content"     android:layout_gravity="center"     android:stretchColumns="*"> <TableRow>         <Button         android:id="@+id/countbutton"         android:text="@string/plus1"/>           <Button         android:id="@+id/resetbutton"         android:text="@string/reset"          />   </TableRow> </TableLayout> 

And now what I dont get - the WIDTH of one row and also of the button depends on the TEXT inside the button. If the both texts are equaly long lets say : TEXT its ok - the table half is in the middle of the screen. But if they have different size - lets say "A" and "THIS IS THE LONG BUTTON" the CENTER of the table isnt in the middle of the screen anymore and so the buttons are not equally width...

like image 236
Oliver Goossens Avatar asked May 19 '10 12:05

Oliver Goossens


2 Answers

To have buttons in rows where buttons are the same size you need to do.

    <LinearLayout android:orientation="horizontal"           android:layout_width="fill_parent"          android:layout_height="fill_parent">          <Button android:layout_weight="1"               android:layout_height="wrap_content"               android:layout_width="0dip"/>          <Button android:layout_weight="1"               android:layout_height="wrap_content"               android:layout_width="0dip"/>     </LinearLayout> 

And fill in the other xml properties for your buttons.

The magic is in the layout_weight and width properties. You don't need the Table layout. These properties tell the layout that your views should take up equal space in the parent layout.

like image 71
Robby Pond Avatar answered Oct 08 '22 23:10

Robby Pond


In addition to the accepted answer:

I had a similar problem where I needed several images in a grid with equal column widths, so I used a table layout. It worked, but as the images loaded asynchronously, the corresponding columns would take up the entire width until all columns had at least one image in them.

I solved this using Robby Pond's solution, but it didn't work for the last row, which didn't necessarily have as many images as the other rows, stretching those images to take up all available space when I wanted them to fit in the same columns as above. To combat this, I filled the remaining empty columns of that row with regular View objects,

using the same layout parameters as all the other images:

width = 0, weight = 1. And that solved it!

like image 44
may5694 Avatar answered Oct 09 '22 01:10

may5694