0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.