言いたいことはそれだけか

KotlinとかAndroidとかが好きです。調べたことをメモします。٩( 'ω' )و

ConstraintLayout 2.0でFlexboxLayoutとGridLayoutを代用する

はじめに

ConstraintLayout 2.0から導入された Flow を使ってFlexboxLayoutやGridLayoutと同じようなことができるようになる。

androidstudio.googleblog.com

developer.android.com

こんな感じでできた。
(上がFlexboxLayoutっぽいやつ、下がGridLayoutっぽいやつ)

f:id:muumuumuumuu:20190928193852p:plain:w200

ConstraintLayoutは 2.0.0-beta2 を使っている。 コードサンプルはこちら

github.com

FlexboxLayoutっぽいのを作ってみる

<androidx.constraintlayout.helper.widget.Flow
    android:id="@+id/flexbox_flow"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_margin="16dp"
    android:orientation="horizontal"
    app:constraint_referenced_ids="text_1,text_2,text_3,text_4,text_5"
    app:flow_wrapMode="chain"
    app:flow_horizontalStyle="packed"
    app:flow_verticalStyle="packed"
    app:flow_horizontalGap="8dp"
    app:flow_verticalGap="8dp"
    app:flow_firstHorizontalBias="0"
    app:flow_horizontalBias="0"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toTopOf="@id/grid_flow"
    />

配置したい要素となるviewとは別に Flow を定義してやる。以下各attributeの説明

  • 要素は app:constraint_referenced_ids でカンマ区切りで指定
  • FlexboxLayoutっぽくするポイントは app:flow_wrapModechain を指定すること
  • app:flow_horizontalStyleapp:flow_verticalStylepacked を指定しているので詰めて表示される
  • 各要素のmerginは app:flow_horizontalGapapp:flow_verticalGap で指定
  • layout_constraintHorizontal_bias などが効かないので、代わりに app:flow_horizontalBias を使う

GridLayoutっぽいのを作ってみる

    <androidx.constraintlayout.helper.widget.Flow
        android:id="@+id/grid_flow"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="16dp"
        android:orientation="horizontal"
        app:constraint_referenced_ids="number_1,number_2,number_3,number_4,number_5,number_6,number_7,number_8,number_9"
        app:flow_wrapMode="aligned"
        app:flow_maxElementsWrap="3"
        app:flow_horizontalGap="4dp"
        app:flow_verticalGap="4dp"
        app:layout_constraintTop_toBottomOf="@id/flexbox_flow"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        />

FlexboxLayoutっぽい方とほとんど一緒だが、違いは app:flow_wrapModealigned を指定すること。あと、1行(orientationがverticalの場合は1列)にいくつ要素を配置するかを app:flow_maxElementsWrapで指定する。

終わりに

かなり使いやすい印象なので、早くbetaが取れて欲しい。FlexboxLayoutとGridLayoutではなくてConstraintLayoutを使う理由は何かあるのかと思う人がいるかもしれないが、個人的にはこの辺りの理由でConstraintLayoutを推す。

  • デザイン変更が容易にできる(各要素は変更せず、Flowだけの変更で対応できる。運がよければだけど)
  • Layoutがnestしないのでパフォーマンス観点で期待できる(計測して無いですごめんなさい)
  • 同じくConstraintLayout 2.0 から追加された LayerCircular Reveal などのdecoratorが使いたくなるかも?