[英]How do i set cell height to be as it's width in 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 b1 = (Button) findViewById(R.id.b1);
b1.setHeight(b1.getWidth());
但它不起作用(它給我的值為0)。 我猜想是因為當我這樣做時(在onCreate方法中)按鈕尚未設置。
首先,您是對的,您將獲得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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.