Jetpack Compose 入门:LazyVerticalGrid & LazyHorizontalGrid

LazyVerticalGridLazyHorizontalGrid 用于显示 Grid 列表;

GridCells.Fixed() 设置要显示的列数;

rememberLazyGridState() 获取滚动状态;

horizontalArrangementverticalArrangement 设置间距。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@Composable
fun GridScreen(
modifier: Modifier = Modifier
) {
val lazyVerticalGridState = rememberLazyGridState()
val lazyHorizontalState = rememberLazyGridState()

val list = listOf(1,2,3,4,5,6,7,8,9,10)

Column(
modifier = modifier.fillMaxWidth()
) {
LazyHorizontalGrid(
modifier = modifier.height(120.dp),
rows = GridCells.Fixed(2),
state = lazyHorizontalState,
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
content = {
items(
items = list,
){item ->
Text(
text = "Grid $item",
modifier = modifier
.height(50.dp)
.width(100.dp)
.background(Color.Yellow),
)
}
}
)

LazyVerticalGrid(
columns = GridCells.Fixed(2),
state = lazyVerticalGridState,
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
content = {
items(
items = list,
){item ->
Text(
text = "Grid $item",
modifier = modifier
.height(200.dp)
.width(100.dp)
.background(Color.Green),
)
}
}
)
}
}

参考文档 列表和网格

Demo:https://github.com/hefengbao/jetpack-compose-demo