[Android] Create a square view while maintaining the aspect ratio: SquareLayout

Let's create a Custom View called SquareLayout

public class SquareLayout extends LinearLayout {

    public SquareLayout(Context context) {
        super(context);
    }

    public SquareLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}

Use it in the layout as follows.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <com.your-package.SquareLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/something_item1" />

    </com.your-package.SquareLayout>

    <com.your-package.SquareLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginLeft="15dp">

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/something_item2" />

    </com.your-package.SquareLayout>

    <com.your-package.SquareLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginLeft="15dp">

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/something_item3" />

    </com.your-package.SquareLayout>

    <com.your-package.SquareLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginLeft="15dp">

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/something_item4" />

    </com.your-package.SquareLayout>

</LinearLayout>

I was able to arrange four square buttons like this.

The original was stackoverflow here.

Recommended Posts

[Android] Create a square view while maintaining the aspect ratio: SquareLayout
[Kotlin / Android] Create a custom view
A newcomer tries to summarize the Android view (beginner Android application development)
[Android] Create a calendar using GridView