LoginSignup
2
0

More than 1 year has passed since last update.

【Jetpack Compose】LazyVerticalGridを扱う

Posted at

LazyVerticalGridを使う際に以下の動画のようなレイアウトを実装するときに苦戦し、注意点がいくつかあったので書いておきます。

  • 検索バーは1列で表示
  • 画像は3列で表示
  • 下にスクロールすると検索バーもスクロールされる

Videotogif.gif

LazyVerticalGridとは

LazyVerticalGridを使うことでアイテムをグリッド表示することができます。

GridCellsにグリッド表示したい列数を渡すことでレイアウトを制御することができます

LazyVerticalGrid(cells = GridCells.Fixed(3)) {

LazyVerticalGridのスコープ内でコンポーザブルを使用する場合はitemもしくはitemsを使用して配置していきます

LazyVerticalGrid(cells = GridCells.Fixed(3)) {
    item {
        Text()
    }
}

特定のアイテムのみ1行にする実装

最初に紹介した動画では検索バーもスクロールに含まれるため、LazyVerticalGridのスコープ内に入れる必要がありました。列数を固定しないときは、そのアイテムにGridItemSpan(maxCurrentLineSpan)を設定することで実装できました。

LazyVerticalGrid(cells = GridCells.Fixed(3)) {
        item(span = { GridItemSpan(maxCurrentLineSpan) }) {
            SearchBar(query = "")
        }
        itemsIndexed(items = (1..50).map { ImageData(index = it) }) { index, item ->
            Image(painter = painterResource(id = item.image), contentDescription = null)
        }
    }

1つのアイテムに複数の要素を入れない

以下のコードのように、1つのitemの中にColumnで複数のコンポーザブルを配置するのは個別にコンポーズすることができなくなり、パフォーマンス的に良くないそうです。またscrollToItem()animateScrollToItem()にも影響が及ぶみたいです。(ドキュメント)

LazyVerticalGrid(cells = GridCells.Fixed(3)) {
        item(span = { GridItemSpan(maxCurrentLineSpan) }) {
           Column {
                SearchBar(query = "")
                TrendKeyword()
            }
        }
        itemsIndexed(items = (1..50).map { ImageData(index = it) }) { index, item ->
            Image(painter = painterResource(id = item.image), contentDescription = null)
        }
    }
2
0
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
2
0