横向列表LazyRow
LazyRow和LazyColumn使用类似。
/**
* 横向列表LazyRow
*/
@Composable
fun LazyRowTest() {
val context = LocalContext.current
val dataList = arrayListOf<Int>()
for (index in 1..50) {
dataList.add(index)
}
LazyRow {
items(dataList) { data ->
Box(
modifier = Modifier
.fillMaxHeight()
.padding(start = 1.dp)
.background(Color.White)
.clickable {
Toast
.makeText(context, "$data", Toast.LENGTH_SHORT)
.show()
}
.padding(10.dp),
) {
Text(
text = "第${data}条数据",
modifier = Modifier.align(Alignment.Center), // 设置上下居中
)
}
}
}
}
垂直网格布局LazyVerticalGrid
垂直网格布局使用LazyVerticalGrid组件,GridCells.Adaptive以最小宽度设置横向排列数量,GridCells.Fixed直接设置横向排列数量。
/**
* 垂直网格布局(纵向滑动)
*/
@Composable
fun LazyVerticalGridTest() {
val photos = arrayListOf<Int>()
for (index in 0..50) {
photos.add(R.drawable.img)
}
LazyVerticalGrid(
//以最小宽度设置横向排列数量
// columns = GridCells.Adaptive(minSize = 120.dp)
//直接设置横向排列数量
columns = GridCells.Fixed(count = 3)
) {
items(photos) { photo ->
Image(
painter = painterResource(photo),
"",
modifier = Modifier.padding(2.dp)
)
}
}
}
水平网格布局LazyHorizontalGrid
水平网格布局和垂直网格布局类似,只是纵向滑动变成了横向滑动,属性值和垂直网格布局相反。
/**
* 水平网格布局(横向滑动)
*/
@Composable
fun LazyHorizontalGridTest() {
val photos = arrayListOf<Int>()
for (index in 0..50) {
photos.add(R.drawable.img)
}
LazyHorizontalGrid(
//以最小大小设置纵向排列数量
rows = GridCells.Adaptive(minSize = 120.dp)
//设置纵向排列数量
// rows = GridCells.Fixed(count = 6)
) {
items(photos) { photo ->
Image(
painter = painterResource(photo),
"",
modifier = Modifier.padding(5.dp)
)
}
}
}