LoginSignup
1
3

More than 5 years have passed since last update.

【Android】アスペクト比を維持して正方形のViewを作る:SquareLayout

Posted at

SquareLayoutというCustom Viewを作りましょう

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);
    }
}

layoutの中で以下のように使います。

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

こんな感じで正方形の4つのボタンを配置できました。

原典はこちらのstackoverflowでした。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3