How to make perfect square shaped image/button How to make perfect square shaped image/button xml xml

How to make perfect square shaped image/button


Change the wrap_contents to a default size:

android:layout_width="wrap_content"android:layout_height="wrap_content"

to

android:layout_width="@dimen/box_size"android:layout_height="@dimen/box_size"

(and then set the box_size in the res/values/dimen.xml like: <dimen name="box_size">50dp</dimen>)


OR, use wrap_content for the width, and then in code use myBox.setHeight(myBox.getMeasuredWidth); so the width and height match. Just make sure the view is completely loaded though, otherwise getMeasuredWidth returns 0.

EDIT:

To change the height to match the wrap_content width after the View is loaded, you can use a ViewTreeObserver:

if(yourActivityLayout.getViewTreeObserver().isAlive()){    yourActivityLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {        @Override        public void onGlobalLayout(){            // The view is completely loaded now, so getMeasuredWidth() won't return 0            yourButton1.setLayoutParams(new TableLayout.LayoutParams(yourButton1.getMeasuredWidth(), yourButton1.getMeasuredWidth()));            ... // Do this for all buttons (preferably in a for-loop to prevent repetition)            // Destroy the onGlobalLayout afterwards, otherwise it keeps changing            // the sizes non-stop, even though it's already done            yourActivityLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);        }    });}


Button code in XML

<Button    android:id="@+id/btn"      android:layout_width="64dp"    android:layout_height="64dp"    android:background="@drawable/buttonshape"/>

buttonshape.xml code

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"  android:shape="rectangle" ><cornersandroid:topLeftRadius="0dp"android:topRightRadius="0dp"android:bottomLeftRadius="0dp"android:bottomRightRadius="0dp"/><solidandroid:color="#0000ff"/><paddingandroid:left="0dp"android:top="0dp"android:right="0dp"android:bottom="0dp"/><sizeandroid:width="64dp"android:height="64dp"/></shape>


Try to add fixed width and height.

 android:layout_width="@dimen/box_size" android:layout_height="@dimen/box_size"

and in res/values/dimen.xml add

 <dimen name="box_size">40dp</dimen>