使用列表
fun ScrollingView()相当于recyclerview (原本是ScrollingList)
依赖:用于加载网络图片
implementation 'io.coil-kt:coil-compose:1.4.0'
painter = rememberImagePainter(
data = "https://tse4-mm.cn.bing.net/th/id/OIP-C.W_ojBE429JEt_UbsoDk6YQAAAA?pid=ImgDet&rs=1"),
使用前提是加载网络权限
@Preview
@Composable
fun ScrollingView(){
val listSize = 100
val scrollState = rememberLazyListState()
//协程作用域,作用域消失,则作用域中的协程都会被取消
val coroutineScope = rememberCoroutineScope()
Column {
Row {
Button(
modifier = Modifier.weight(1f),
onClick = {
//animateScrollToItem为挂起函数suspend,只能在另一个挂起函数或协程内调用
coroutineScope.launch {//拿到协程作用域
scrollState.animateScrollToItem(0)
}
}
) {
Text(text = "Scroll to the top")
}
Button(
modifier = Modifier.weight(1f),
onClick = {
coroutineScope.launch {//拿到协程作用域
scrollState.animateScrollToItem(listSize-1)
}
}
) {
Text(text = "Scroll to the end")
}
}
LazyColumn(state = scrollState){
items(listSize){
ImageListItem(index = it)
}
}
}
}
@Composable
fun ImageListItem(index : Int){
Row(verticalAlignment = Alignment.CenterVertically) {
//coil加载网络图片,coil官网2022年12.30日显示的是AsyncImage
//依赖最新版本2.2.2,但是会报错,和kotlin版本不兼容,调到了2.0.0运行
AsyncImage(
model = "https://developer.android.google.cn/images/brand/Android_Robot.png",
contentDescription = null,
modifier = Modifier.size(50.dp)
)
Spacer(modifier = Modifier.size(10.dp))
Text(text = "Item # $index", style = MaterialTheme.typography.subtitle1)
}
}
标签:modifier,compose,协程,作用域,jetpack,学习,coil,Modifier,scrollState
From: https://www.cnblogs.com/vvvv214/p/17014593.html