your3i’s blog

iOSエンジニア。頑張る⚉

Androidのconstraint layoutで、画面横サイズ何パーセントのビューに対して最大横幅を指定したいとき

layout_constraintWidth_percent と(android:maxWidth と layout_constraintWidth_max)の併用はできない。guidelineを使って横何パーセントを作ると、layout_constraintWidth_maxが効くようになる。

例えば

以下のように、image view を画面横サイズの60%にし、最大横幅160dpにし、縦横アスヒは1:1で、横真ん中に置き、上から16dp(図に描いてない)のレイアウトにしたい。
f:id:your3i:20181124185002p:plain

guideline を貼る

Guidelineを以下のようにimage viewの左右に貼る。Guidelineたちがimage viewを横サイズの60%になれるように引っ張る。その上で、layout_constraintWidth_maxを設定すると、最大横幅の指定ができる。

f:id:your3i:20181124185937p:plain

コードの方
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline_imageview_start"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                app:layout_constraintGuide_percent="0.2" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline_imageview_end"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                app:layout_constraintGuide_percent="0.8" />

            <ImageView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginTop="16dp"
                android:contentDescription="@null"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintEnd_toStartOf="@id/guideline_imageview_end"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintStart_toEndOf="@id/guideline_imageview_start"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintWidth_max="160dp" />

        </androidx.constraintlayout.widget.ConstraintLayout>