列表下拉刷新
- material3 还没有下拉刷新功能
- material:1.3.0 之后 swiperefresh 被弃用 被PullRefresh替代
- 使用PullRefresh 需要添加依赖 implementation 'androidx.compose.material:material:1.6.8'
先上代码
var refreshing by remember {
mutableStateOf(false)
}
val list = remember{
List(10){"条目》》${it}"}.toMutableStateList()
}
val scope = rememberCoroutineScope()
val refreshState = rememberPullRefreshState(refreshing = refreshing, onRefresh = {
scope.launch {
refreshing = true
list.addAll( List(20){
delay(100)
"新的条目》》${it}"
})
refreshing = false
}
})
Box(modifier = Modifier
.pullRefresh(refreshState)
.padding(20.dp)){
LazyColumn(modifier = Modifier.fillMaxSize()){
items(list){
Text(text = "条目>>${it}")
}
}
PullRefreshIndicator(refreshing = refreshing, state = refreshState,modifier=Modifier.align(
Alignment.TopCenter
))
}
再看效果
- 默认列表10条
- 下拉刷新时 协程添加20条 每条延时100ms后刷新结束
接着分析
fun Modifier.pullRefresh(
state: PullRefreshState, //刷新状态的回调
enabled: Boolean = true
)
上边是让我们使用rememberPullRefreshState,那么我们就听话看看rememberPullRefreshState
@Composable
@ExperimentalMaterialApi
fun rememberPullRefreshState(
refreshing: Boolean, //当前是否正在刷新
onRefresh: () -> Unit, //刷新时调用此函数
refreshThreshold: Dp = PullRefreshDefaults.RefreshThreshold,
refreshingOffset: Dp = PullRefreshDefaults.RefreshingOffset,
): PullRefreshState {
接着我们看看 PullRefreshIndicator
fun PullRefreshIndicator(
refreshing: Boolean, //A boolean representing whether a refresh is occurring.
state: PullRefreshState, //刷新时的回调函数
modifier: Modifier = Modifier,
backgroundColor: Color = MaterialTheme.colors.surface,
contentColor: Color = contentColorFor(backgroundColor),
scale: Boolean = false
) {
如果我们注释掉PullRefreshIndicator
结果
- 没有了刷新的指示器
- 依然可以刷新列表
说明:
- PullRefreshIndicator只是用来显示当前是否正在刷新状态的指示器
- 执行列表刷新的还是Modifer.pullRefresh
于是乎 开玩
// PullRefreshIndicator(refreshing = refreshing, state = refreshState,modifier=Modifier.align(
// Alignment.TopCenter
// ))
AnimatedVisibility(visible = refreshing,modifier = Modifier.align(Alignment.TopCenter)){
CircularProgressIndicator(
modifier = Modifier.width(64.dp),
color = MaterialTheme.colorScheme.secondary,
)
}`
结果