どうも。どっことです。今回はFlexboxLayout
の使い方を解説します。
FlexboxLayoutを使う
タグやキーワードの一覧などに、Webサイトの見せ方の一つとして利用されている表示方法ですが、AndroidでもFlexboxLayout
というViewGroupで同様の表示が提供されています。今回はこちらのコンポーネントの使い方について解説します。
FlexboxLayoutを使ったレイアウトの実装方法
以下の順で利用方法について解説します。
- ライブラリを追加する。
FlexboxLayout
をレイアウトとして利用する。- 表示確認
ライブラリを追加する
ライブラリを追加します。build.gradle
のdependencies
に以下を追加します。
dependencies {
implementation 'com.google.android.flexbox:flexbox:3.0.0'
}
FlexboxLayoutをレイアウトとして利用する
FlexboxLayout
をレイアウトとして利用します。LinearLayoutやConstraintLayoutと同様に、レイアウト内に組み込みます。
<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"
を設定してください。このとき、appのnamespaceが定義されていないせいで赤文字表示される場合はnamespace定義を追加してください。(ctrl
+ Enter
で大体解決してくれる)
表示確認
上記で実装すると、以下のように表示されます。
長いテキストが設定されているTextViewが折り返された位置で表示されているのが見てわかると思います。
まとめ
今回はFlexboxLayout
の使い方について解説しました。