0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FlowRowを利用したGridViewのようなUIについて

Last updated at Posted at 2022-12-06

はじめに

FlowLayoutとはGoogleのAccompanistが提供している中の一つのライブラリです。
画面幅に対して折り返していくようなUIを提供しています。FlowRowFlowColumnというComposableが提供されております。この記事では水平方向に折り返していくFlowRowを使ったGirdViewのようなUIを表現してみたいと思います。

やりたいこと

ComposeでGridView的な表現をしたい場合、LazyVerticalGridがありますが、リストの長さが可変の場合や、スクロールの中でリスト表示以外のUIを差し込みたい場合、LazyVerticalGridだと簡単ではなさそうだなと思い、FlowRowをつかってみました。イメージとしては以下のような2列の可変長リストとそれ以外のUIが混ざったようなスクロールできるUIを実装してみたいと思います。
sankou2.png

導入

導入自体は非常に簡単でbuild.gradleに以下を指定するだけです。
$flowVersionは現在の最新は0.28.0のようです。

repositories {
    mavenCentral()
}

implementation "com.google.accompanist:accompanist-flowlayout:$flowVersion"

実装

FlowRowを使った実装です。

@Composable
fun FlowSample() {
    FlowRow(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 18.dp),
        mainAxisSize = SizeMode.Wrap,
        mainAxisSpacing = 7.dp,
        crossAxisAlignment = FlowCrossAxisAlignment.Start,
        crossAxisSpacing = 7.dp,
    ) {
        for (i in 0..9) {
            Card(i)
        }
    }
}

FlowRowのスコープ内でforループ分、子要素を追加します。サンプルなので固定ですがViewModelなどからリストを受け取るといったイメージです。
ちなみにmainAxisSpacingは主軸のスペース長、crossAxisSpacingは横軸のスペース長です。
crossAxisAlignmentはAlignmentでStartを指定することで折り返さない場合、画面左に子のUIが配置されます。ちなみにCardの部分の実装は固定のサイズをもった適当なUIです。

全体的な実装も至ってシンプルです。ColumnverticalScrollを指定し、このスコープ内でFlowRowやUIを実装していくのみです。

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .verticalScroll(scrollState)
        horizontalAlignment = Alignment.CenterHorizontally,
    ){
        Spacer(modifier = Modifier.height(56.dp))
        FlowSample()
        Spacer(modifier = Modifier.height(10.dp))
        SomeMiddleContent()
        Spacer(modifier = Modifier.height(10.dp))
        FlowSample()
        Spacer(modifier = Modifier.height(80.dp))
    }

上記のサンプルは以下のような見た目になります。
flowsample.gif

要素であるCard()の部分が固定長なのもあり、解像度によっては折り返してしまい1列や3列の見た目になる可能性もあるため、実際には端末のwidthを考慮して幅を決定していく必要などがあります。

まとめ

FrowRowを使うことで若干複雑なコンテンツがあるGridView的な表現が比較的簡単に実現できました。
ただ、自分がLazyVerticalGridなどの知見のあまりないため、もしかするともっと最適なやりかたがあるかもしれません。

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?