用compose实现下拉刷新上拉加载更多
时间: 2024-01-26 09:48:29 浏览: 29
下拉刷新和上拉加载更多是很常见的列表操作,可以通过使用 `compose-ui` 库中提供的 `LazyColumn` 和 `SwipeRefresh` 组件来实现。
下面是一个简单的示例代码,实现了下拉刷新和上拉加载更多的功能:
```kotlin
@Composable
fun RefreshableList(items: List<String>, onRefresh: () -> Unit, onLoadMore: () -> Unit) {
var isLoading by remember { mutableStateOf(false) }
val scrollState = rememberLazyListState()
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = scrollState,
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(items = items) { item ->
Text(text = item, fontSize = 16.sp)
}
if (isLoading) {
item {
CircularProgressIndicator(
modifier = Modifier
.wrapContentWidth()
.align(Alignment.CenterHorizontally)
)
}
}
}
SwipeRefresh(
state = rememberSwipeRefreshState(isRefreshing = false),
onRefresh = {
onRefresh()
}
) {
if (scrollState.isScrolledToBottom() && !isLoading) {
isLoading = true
onLoadMore()
}
}
}
```
在上面的代码中,`RefreshableList` 函数接收一个字符串列表和两个回调函数 `onRefresh` 和 `onLoadMore`,分别是下拉刷新和上拉加载更多的回调。
在 `LazyColumn` 中,我们使用 `items` 函数来渲染列表项,并在列表末尾添加了一个加载指示器,当 `isLoading` 变量为 true 时显示。
在 `SwipeRefresh` 中,我们监听了下拉刷新事件,并通过 `rememberSwipeRefreshState` 函数来维护下拉刷新状态。如果用户滚动到列表底部并且 `isLoading` 变量为 false,那么就触发 `onLoadMore` 回调函数,同时将 `isLoading` 变量设置为 true。
这样,我们就实现了一个具有下拉刷新和上拉加载更多功能的列表。