Kotlin Compose 列表 手动控制列表。给Column添加滚动能力 LazyColumn动画滚动到底部
时间:2023-01-05 20:30:00
@Composable fun SimpleColumn() { Column() { repeat(100) { Text(text = "Item #$it", style = MaterialTheme.typography.subtitle1) } } }
有缺陷,无法进行上下滚动
@Composable fun SimpleList() { val scrollState = rememberScrollState() Column(Modifier.verticalScroll(scrollState)) { repeat(100) { Text(text = "Item #$it", style = MaterialTheme.typography.subtitle1) } } }
滑动文字可以滑动,不要滑动空白区域。那还不是Column
滑动红色区域
让我们写一个滚动列表 用按钮控制滚动
添加依赖
加载网络图片
implementation 'io.coil-kt:coil-compose:2.1.0'
@Composable fun ScrollingList() { val scrollState = rememberLazyListState() val coroutineScope = rememberCoroutineScope() val listSize=100 Column() { Row() { Button(modifier = Modifier.weight(1f), onClick = { coroutineScope.launch { scrollState.animateScrollToItem(0) } }) { Text("Scroll to the top") } Button(modifier = Modifier.weight(1f), onClick = { coroutineScope.launch { scrollState.animateScrollToItem(listSize - 1) } }) { Text("Scroll to the end") } } LazyColumn(state = scrollState) { items(listSize) { ImageListItem(it) } } } } @Composable fun ImageListItem(index: Int) { Row(verticalAlignment = Alignment.CenterVertically) { Image( painter = rememberImagePainter(data = "https://gimg2.baidu.com/image_search/src=http://pic1.win4000.com/wallpaper/2020-10-12/5f83b7c13d0b9.jpg&refer=http://pic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657808691&t=3a05e7dad6f14402a7c14354e302f51b"), modifier = Modifier.size(50.dp), contentDescription = null ) Spacer(modifier = Modifier.width(10.dp)) Text(text = "Item #$index", style = MaterialTheme.typography.subtitle1) } }
这里用到了
网络图片
rememberImagePainter
这个东西有什么用?
加载网络图片
似乎弃用了
推荐这种写法
@Composable fun ImageListItem(index: Int) { Row(verticalAlignment = Alignment.CenterVertically) { Image( painter = rememberAsyncImagePainter( "https://gimg2.baidu.com/image_search/src=http://pic1.win4000.com/wallpaper/2020-10-12/5f83b7c13d0b9.jpg&refer=http://pic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657808691&t=3a05e7dad6f14402a7c14354e302f51b"), modifier = Modifier.size(50.dp), contentDescription = null ) Spacer(modifier = Modifier.width(10.dp)) Text(text = "Item #$index", style = MaterialTheme.typography.subtitle1) } }
点击按钮控制滚动 很好玩。