Jetpack Compose中的列表组件

前言

Jetpack Compose 中的列表组件相对于之前的View方式要简单很多。

竖向列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Composable
fun MyList(mList: List<String>){
LazyColumn {
items(mList.size){
ListItem(mList[it])
}
}
}

@Composable
fun ListItem(text: String) {
// 构建列表项的 UI
Text(text = text)
}

调用

1
MyList(listOf("张三","李四","王五"))

注意

新版本的items方法参数变了。

横向列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Composable
fun MyList(mList: List<String>){
LazyRow {
items(mList.size){
ListItem(mList[it])
}
}
}

@Composable
fun ListItem(text: String) {
// 构建列表项的 UI
Text(text = text)
}

调用

1
MyList(mutableListOf<String>("A", "B", "C"))

设置间距

1
horizontalArrangement= Arrangement.spacedBy(10.dp)

竖向Grid

基本示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Composable
fun MyGridList(mList: List<String>) {
LazyVerticalGrid(columns = GridCells.Fixed(2)) {
items(mList.size) { index ->
// 在这里构建您的列表项
GridItem(text = mList[index])
}
}
}

@Composable
fun GridItem(text: String) {
// 构建列表项的 UI
Card(
modifier = Modifier.padding(16.dp).height(30.dp),
) {
Text(text)
}
}

注意

竖向Grid布局中的子项,也就是上面的GridItem中的根组件的宽度是自动使用父的,设置宽度不会生效。

横竖屏不同列数

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
import android.content.res.Configuration
import androidx.compose.ui.platform.LocalConfiguration

@Composable
fun MyGridList(mList: List<String>) {
val configuration = LocalConfiguration.current
val isLandscape = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
val columnCount = if (isLandscape) 2 else 1
LazyVerticalGrid(columns = GridCells.Fixed(columnCount)) {
items(mList.size) { index ->
// 在这里构建您的列表项
GridItem(text = mList[index])
}
}
}

@Composable
fun GridItem(text: String) {
// 构建列表项的 UI
Card(
modifier = Modifier.padding(16.dp).height(30.dp),
) {
Text(text)
}
}

自适应列数

这种方式好在,它能自适应进行布局。

假如页面的宽度是700dp,我们设置minSize = 300.dp,这样它会自动变成两列,每列350dp

如果页面的宽度变成了500dp,那么就会变成一列,列的宽度也是500dp

总之还是比较智能的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Composable
fun AppListView(mList: List<AppModel>) {
LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 300.dp),
contentPadding = PaddingValues(10.dp),
verticalArrangement = Arrangement.Top
) {
items(mList.size,key = {item -> item }) {
Box(
modifier = Modifier
.padding(10.dp)
.fillMaxSize()
) {
AppListItem(mList[it])
}
}
}
}

设置间距

1
2
3
4
5
6
7
8
9
LazyVerticalGrid(
columns = GridCells.Fixed(2),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
items(photos) { item ->
PhotoItem(item)
}
}

横向Grid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Composable
fun MyGridList(mList: List<String>) {
LazyHorizontalGrid(rows = GridCells.Fixed(2)) {
items(mList.size) { index ->
// 在这里构建您的列表项
GridItem(text = mList[index])
}
}
}

@Composable
fun GridItem(text: String) {
// 构建列表项的 UI
Card(
modifier = Modifier.padding(16.dp).height(30.dp),
) {
Text(text)
}
}

注意

竖向Grid布局中的子项,也就是上面的GridItem中的根组件的高度是自动使用父的,设置高度不会生效。