FlexboxLayoutを扱う
実装手順
- ライブラリを追加する。
FlexboxLayoutをレイアウトに組み込む。- 表示を確認する。
1. ライブラリを追加する
まず、app/build.gradleファイルのdependenciesに以下のライブラリを追加する。
dependencies {
implementation 'com.google.android.flexbox:flexbox:3.0.0'
}
2. FlexboxLayoutをレイアウトとして利用する
LinearLayoutやConstraintLayoutと同じように、レイアウトファイルに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