简体   繁体   中英

Android: UI Linear Layout and Buttons

I am having 8(Eight) buttons in one line(horizontal) under one linear layout. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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