效果图:
使用代码:
PullRefreshLazyColumn(count = list.size, onRefresh = {
// 执行刷新操作,比如去http查询数据。
}) { index ->
val item = list.value[index]
Text(text = "item:$item")
}
封装代码:
@Composable
fun PullRefreshLazyColumn(
modifier: Modifier = Modifier,
isRefreshing: MutableState<Boolean> = remember { mutableStateOf(false) },
headHeight: Dp = 50.dp,
head: @Composable BoxScope.(Float, Modifier) -> Unit = { progress, m ->
RefreshDefaultHead(
progress,
m
)
},
headProgress: @Composable BoxScope.() -> Unit = { RefreshDefaultProgress() },
count: Int,
onRefresh: suspend () -> Unit,
item: @Composable LazyItemScope.(Int) -> Unit
) {
val scope = rememberCoroutineScope()
val pullRefreshState = rememberPullRefreshState(refreshing = isRefreshing.value, onRefresh = {
scope.launch {
isRefreshing.value = true
onRefresh()
isRefreshing.value = false
}
})
Column(
modifier = Modifier
.then(modifier)
.pullRefresh(pullRefreshState)
) {
if (isRefreshing.value) {
Box(modifier = Modifier
.align(Alignment.CenterHorizontally)
.height(headHeight.value.dp)) {
headProgress()
}
} else {
var height = pullRefreshState.progress * headHeight.value
if (height > headHeight.value) {
height = headHeight.value
}
Box(
modifier = Modifier
.height(height.dp)
.align(Alignment.CenterHorizontally)) {
head(pullRefreshState.progress, Modifier.height(height.dp))
}
}
LazyColumn {
items(count = count) { index ->
item(index)
}
}
}
}
@Composable
private fun BoxScope.RefreshDefaultHead(progress: Float, modifier: Modifier) {
Row(
modifier = Modifier
.then(modifier)
.align(Alignment.Center)
) {
var text = "下拉刷新"
val rotate = if (progress > 1) {
text = "松开刷新"
1f
} else {
progress
} * 180 - 90
Image(
imageVector = Icons.Default.ArrowBack,
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.rotate(rotate)
.size(25.dp)
.align(Alignment.CenterVertically)
)
Text(
text = text, modifier = Modifier
.align(Alignment.CenterVertically)
)
}
}
// 下拉刷新正在刷新的UI
@Composable
private fun BoxScope.RefreshDefaultProgress() {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}