どっこと備忘録群

アウトプットしないとインプットできない私が Androidアプリ開発をメインとした備忘録を載せています。

FlexboxLayoutを扱う

実装手順

  1. ライブラリを追加する。
  2. FlexboxLayoutをレイアウトに組み込む。
  3. 表示を確認する。

1. ライブラリを追加する

まず、app/build.gradleファイルのdependenciesに以下のライブラリを追加する。

dependencies {
  implementation 'com.google.android.flexbox:flexbox:3.0.0'
}

2. FlexboxLayoutをレイアウトとして利用する

LinearLayoutConstraintLayoutと同じように、レイアウトファイルにFlexboxLayoutを組み込む。

<com.google.android.flexbox.FlexboxLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:flexWrap="wrap">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="テキスト1"
        android:padding="16dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="テキスト2 少し長め"
        android:padding="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="テキスト3"
        android:padding="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="テキスト4 長くなったら折り返される"
        android:padding="16dp" />
            
</com.google.android.flexbox.FlexboxLayout>

ポイント: FlexboxLayoutの属性にapp:flexWrap="wrap"を設定する。 これにより、子ビューが親ビューの端に達したときに次の行に折り返される。

参考

最終更新: 2025.9.7