Compose中Paging3、SwipeRefresh配合实现下拉刷新和自动加载

本文介绍如何在Jetpack Compose中使用Paging3组件实现数据分页加载及刷新功能,包括配置PagingSource、ViewModel及LazyColumn的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关注公众号学习更多知识

概述

Compose中Paging3的使用和Recycleview中Paging3的使用基本一致,不同的是Compose中我们的ui使用LazyColumn来承载数据。

我们需要做的事情如下:

  • 配置PagingSource
  • 配置数据类SimpleUseBean
  • 配置ViewModel
  • 在LazyColumn中渲染数据

简单加载数据

依赖

 var paging_version = "3.0.1"
    implementation("androidx.paging:paging-runtime:$paging_version")
    testImplementation("androidx.paging:paging-common:$paging_version")
    implementation("androidx.paging:paging-compose:1.0.0-alpha12")

数据类

data class SimpleUseBean(val data: String="")

ViewModel

class SimpleUseViewModel : ViewModel() {
    val projects = Pager(PagingConfig(pageSize = 20)){
        SimpleUseSource()
    }.flow.cachedIn(viewModelScope)
}

配置PagingSource


class SimpleUseSource : PagingSource<Int, SimpleUseBean>() {
    override fun getRefreshKey(state: PagingState<Int, SimpleUseBean>): Int? =null

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, SimpleUseBean> {
        return try {
            val nextPage = params.key ?: 1
            val datas = mutableListOf(
                SimpleUseBean("哈哈${params.key}"),
                SimpleUseBean("哈哈${params.key}"),
                SimpleUseBean("哈哈${params.key}"),
                SimpleUseBean("哈哈${params.key}"),
                SimpleUseBean("哈哈${params.key}")
            )
            LoadResult.Page(
                data = datas,
                prevKey = if (nextPage == 1) null else nextPage - 1,
                nextKey = if (nextPage < 100) nextPage + 1 else null
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}

渲染数据

@Composable
fun simpleUse() {
    val model = viewModel<SimpleUseViewModel>()
    val datas = model.projects.collectAsLazyPagingItems()
    LazyColumn(content = {
        itemsIndexed(datas) { _, data ->
            Box(
                Modifier
                    .padding(horizontal = 14.dp,vertical = 4.dp)
                    .fillMaxWidth()
                    .height(60.dp)
                    .border(1.dp, Color.Red, RoundedCornerShape(5.dp))
                    .padding(start = 10.dp)
                ,
                contentAlignment = Alignment.CenterStart
            ) {
                Text(text = data?.data ?: "")
            }
        }
    })
}

实现效果

使用Compose、SwipeRefresh、LazyColumn实现刷新和加载数据

依赖

SwipeRefresh依赖

 implementation ("com.google.accompanist:accompanist-swiperefresh:0.18.0")

PagingSource


class RefreshLoadUseSource : PagingSource<Int, RefreshData>() {
    override fun getRefreshKey(state: PagingState<Int, RefreshData>): Int? = null

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, RefreshData> {
        return try {
            val nextPage = params.key ?: 1
            if (nextPage < 13) {
                delay(1500)
                val datas = mutableListOf(
                    RefreshData("哈哈${params.key}"),
                    RefreshData("哈哈${params.key}"),
                    RefreshData("哈哈${params.key}"),
                    RefreshData("哈哈${params.key}"),
                    RefreshData("哈哈${params.key}")
                )
                LoadResult.Page(
                    data = datas,
                    prevKey = if (nextPage == 1) null else nextPage - 1,
                    nextKey = if (nextPage < 100) nextPage + 1 else null
                )
            } else {//超过13条就加载错误
                LoadResult.Error(NullPointerException("空指针"))
            }

        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}

ViewModel和数据实体

data class RefreshData(val data: String)
class RefreshLoadUseViewModel : ViewModel() {
    val datas = Pager(PagingConfig(pageSize = 20)) {
        RefreshLoadUseSource()
    }.flow.cachedIn(viewModelScope)
}

ui代码


@Composable
fun refreshLoadUse() {
    val refreshState = rememberSwipeRefreshState(isRefreshing = false)
    val model = viewModel<RefreshLoadUseViewModel>()
    val collectAsLazyPagingItems = model.datas.collectAsLazyPagingItems()
    SwipeRefresh(state = refreshState, onRefresh = {
        collectAsLazyPagingItems.refresh()
    }) {
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(),
            content = {
                itemsIndexed(collectAsLazyPagingItems) { _, refreshData ->//每个item的展示
                    Box(
                        modifier = Modifier
                            .padding(horizontal = 14.dp, vertical = 4.dp)
                            .fillMaxWidth()
                            .height(50.dp)
                            .background(Color.Green,shape= RoundedCornerShape(8.dp))
                            .border(
                                width = 1.dp,
                                color = Color.Red,
                                shape = RoundedCornerShape(8.dp)
                            )
                            .padding(start = 10.dp),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        Text(text = refreshData?.data ?: "")
                    }
                }
                when (collectAsLazyPagingItems.loadState.append) {
                    is LoadState.Loading -> {//加载中的尾部item展示
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(50.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(text = "加载中。。。")
                            }
                        }
                    }
                    else -> {//加载完成或者加载错误展示的尾部item
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(50.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(text = "--加载完成或加载错误--")
                            }
                        }
                    }
                }

            })
    }
}

实现效果

git: https://github.com/ananananzhuo-blog/ComposePaging3Sample

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值