Kotlin constraintSetでレイアウト制約の比率を動的に変更する

すぐ忘れる系めもです。

条件によってUIを変更したいとき、制約の変更を知っていると非常に便利です。

DimensionRateを動的に変更する

このようなConstraintLayoutの下にあるボタンのlayout_constraintDimensionRatioを動的に変更したい場合

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/laout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        >	
        <Button
            android:id="@+id/button"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintDimensionRatio="h,327:60"

ConstraintSetを生成して、親となる制約をCloneします。

クローンしたセットに新しい制約を割り当てます。

    val ratio = "${type.width}:${type.hRate}"
    val constraintSet = ConstraintSet()
    constraintSet.clone(binding.layout1)
    constraintSet.setDimensionRatio(R.id.button, ratio)
    constraintSet.applyTo(binding.layout1)		

もちろん比率だけでなく他制約も変更可能です。