android 在LazyColumn jetpack compose中,有一些类似于swiperefresh layout的东西需要拉到刷新

v8wbuo2f  于 2022-11-20  发布在  Android
关注(0)|答案(3)|浏览(186)

在jetpack compose中有类似swiperefresh layout的东西可以拉来刷新

70gysomp

70gysomp1#

您可以使用Google's Accompanist库来实现滑动刷新。
样品使用:

val viewModel: MyViewModel = viewModel()
val isRefreshing by viewModel.isRefreshing.collectAsState()

SwipeRefresh(
    state = rememberSwipeRefreshState(isRefreshing),
    onRefresh = { viewModel.refresh() },
) {
    LazyColumn {
        items(30) { index ->
            // TODO: list items
        }
    }
}

文件:https://google.github.io/accompanist/swiperefresh/

xtfmy6hx

xtfmy6hx2#

M21.3.0-beta03开始,有一个新的内置拉入刷新组件,带有**pullRefresh**修饰符。
您可以使用类似于以下内容的内容:

val refreshScope = rememberCoroutineScope()
var refreshing by remember { mutableStateOf(false) }
var itemCount by remember { mutableStateOf(15) }

fun refresh() = refreshScope.launch {
    refreshing = true
    delay(1500)
    itemCount += 5
    refreshing = false
}

val state = rememberPullRefreshState(refreshing, ::refresh)

Box(Modifier.pullRefresh(state)) {
    LazyColumn(Modifier.fillMaxSize()) {
        if (!refreshing) {
            items(itemCount) {
                ListItem { Text(text = "Item ${itemCount - it}") }
            }
        }
    }

    PullRefreshIndicator(refreshing, state, Modifier.align(Alignment.TopCenter))
}

af7jpaap

af7jpaap3#

Google's Accompanist现在已弃用。现在在1.3.0版的合成材料中提供官方支持,请使用以下代码:
我用123标记的行完成了这项工作:

val ptrState= 
   rememberPullRefreshState(viewState.isRefreshing, {viewModel.pullToRefresh()}) // 1

Box(modifier = Modifier
    .fillMaxSize()
    .pullRefresh(ptrState)) { // 2
    LazyColumn(state = rememberLazyListState()) {
        items(
            items = viewState.YOUR_LIST_ITEMS,
            key = { item -> item.id },
            itemContent = {
                YourItemCompose(it)
            })
    }
    PullRefreshIndicator
          (viewState.isRefreshing, ptrState, Modifier.align(Alignment.TopCenter)) // 3
}

viewState.isRefreshing是保存刷新状态的布尔值,viewModel.pullToRefresh()是执行刷新数据的实际工作的方法(例如,再次调用API)
如果您不知道依赖关系:

implementation 'androidx.compose.material:material:1.4.0-alpha02'

相关问题