简体   繁体   English

Android:UI线性布局和按钮

[英]Android: UI Linear Layout and Buttons

I am having 8(Eight) buttons in one line(horizontal) under one linear layout. 我在一个线性布局下的一行(水平)中有8个(八个)按钮。 The problem is that these buttons look like rectangle whereas I want them to look like square. 问题是这些按钮看起来像矩形,而我希望它们看起来像方形。

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

Can someone guide me what needs to be done so that these rectangles become squares. 有人可以指导我需要做什么,以便这些矩形变成正方形。

Instead of setting 而不是设置

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

Assign the values for width and height as 将宽度和高度的值指定为

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

Also remove 也删除

   android:layout_weight="0.125" 

So the code is like 所以代码就像

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

    android:background="#ffffffff" />

It Works! 有用!

If you use fixed dimensions for both width and height, you'll get a square, but you lose the nice auto-sizing LinearLayout does. 如果你使用固定尺寸的宽度和高度,你会得到一个正方形,但你失去了很好的自动调整LinearLayout。 In your case, you don't know the width of each button until after the layout is finished. 在你的情况,你不知道每个按钮的宽度布局完成 ,直到。 The post() method in View is your friend. 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();
    }
});

To make sure buttons size correctly your layout should look something like this: 要确保按钮大小正确,您的布局应如下所示:

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

This only takes care of the first button, but you can figure out how to do the rest. 这只需要处理第一个按钮,但您可以弄清楚如何完成其​​余操作。

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

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