LiorZ
LiorZ

Reputation: 341

How do i set cell height to be as it's width in android TableLayout?

I have TableLayout as following:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:stretchColumns="1">

<TableRow>
  <Button
     android:id="@+id/b1"
     android:layout_width="0dip"
     android:layout_height="fill_parent"
     android:layout_weight="1"
     android:gravity="center" />
  <Button
     android:id="@+id/b2"
     android:layout_width="0dip"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:gravity="center" />
  <Button
     android:id="@+id/b3"
     android:layout_width="0dip"
     android:layout_height="fill_parent"
     android:layout_weight="1"
     android:gravity="center" />
 </TableRow>
</TableLayout>

Each Button has the same width. I want the height of those buttons to be exactly the same as their width. I tried to do it programmally by:

Button b1 = (Button) findViewById(R.id.b1);
b1.setHeight(b1.getWidth());

but it doesn't work (it gave me value of 0). I suppose it because when i do it (inside onCreate method) the button isn't set yet.

Upvotes: 1

Views: 1331

Answers (1)

Ofir A.
Ofir A.

Reputation: 3162

First, you are right, you get value of 0, because the screen didn't draw yet when you try to get the button width.

As I see it, the only possibility to do it like you want, is to give them pre defind value in the XML file.

For example:

  <Button
     android:id="@+id/b1"
     android:layout_width="25dip"
     android:layout_height="25dip"
     android:gravity="center" />

Set the width and height programmally:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

btnWidth = metrics.heightPixels/3 - 50;//gap
btnHeight = btnWidth;

Button b1 = (Button) findViewById(R.id.b1);
b1.setHeight(btnWidth);
b1.setWidth(btnWidth);

Upvotes: 1

Related Questions