如何在android TableLayout中将单元格高度设置为它的宽度?

时间:2012-09-28 16:53:27

标签: android android-tablelayout

我有TableLayout如下:

<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>

每个Button的宽度相同。 我希望这些按钮的高度与它们的宽度完全相同。 我尝试通过以下方式进行编程:

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

但它不起作用(它给了我0的值)。我想是因为当我这样做时(在onCreate方法内),按钮尚未设置。

1 个答案:

答案 0 :(得分:1)

首先,你是对的,你得到0的值,因为当你试图获得按钮width时,屏幕还没有画出。

正如我所看到的,唯一可能的做法就是在XML文件中为它们提供预定值。

例如:

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

以编程方式设置宽度和高度:

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);
相关问题