简体   繁体   English

我如何将单元格高度设置为与Android TableLayout中的宽度相同?

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

I have TableLayout as following: 我有如下的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>

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). 但它不起作用(它给我的值为0)。 I suppose it because when i do it (inside onCreate method) the button isn't set yet. 我猜想是因为当我这样做时(在onCreate方法中)按钮尚未设置。

First, you are right, you get value of 0, because the screen didn't draw yet when you try to get the button width . 首先,您是对的,您将获得0的值,因为当您尝试获取按钮的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. 正如我所看到的,按照您的意愿进行操作的唯一可能性是在XML文件中为其提供预定义值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM