0

我在一个线性布局下的一行(水平)中有 8 个(八个)按钮。问题是这些按钮看起来像矩形,而我希望它们看起来像正方形。

<Button
        android:id="@+id/button25"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:layout_weight="0.125" 
        android:background="#ffffffff" />

有人可以指导我需要做什么才能使这些矩形变成正方形。

4

2 回答 2

1

而不是设置

    android:layout_width="match_parent"
    android:layout_height="match_parent"

将宽度和高度的值分配为

    android:layout_width="160dip"
    android:layout_height="160dip"

同时删除

   android:layout_weight="0.125" 

所以代码就像

       <Button
    android:id="@+id/button25"
    android:layout_width="160dip"
    android:layout_height="160dip"
    android:layout_gravity="right"

    android:background="#ffffffff" />

有用!

于 2013-02-26T17:01:03.020 回答
1

如果你对宽度和高度都使用固定尺寸,你会得到一个正方形,但你会失去 LinearLayout 的自动调整大小。在您的情况下,直到布局完成您才知道每个按钮的宽度。View 中的 post() 方法是你的朋友。

final Button button1 = (Button) findViewById(R.id.button25);
first.post( new Runnable() {
    public void run() {
        LinearLayout.LayoutParams params = 
            (LinearLayout.LayoutParams) button1.getLayoutParams();
        params.height = button1.getWidth();
    }
});

为确保按钮大小正确,您的布局应如下所示:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="5"> <!-- or however many buttons there are -->
    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <!-- other buttons go here -->
</LinearLayout>

这仅处理第一个按钮,但您可以弄清楚如何完成其​​余的操作。

于 2013-02-26T17:32:04.550 回答