【问题标题】:Unable to refresh recyclerView with pagination无法使用分页刷新 recyclerView
【发布时间】:2020-10-31 13:19:57
【问题描述】:

我有一个RecyclerView,里面装满了分页数据。

我需要能够通过SwipeRefreshLayout 刷新它,但到目前为止,我无法这样做。

我已经尝试了很多与此类似的参考,但没有任何成功。另外,为了让你们知道,当我刷新时,数据会被正确检索,但它没有显示在 recyclerView 上......

另外,当我通过Navigation 从那个目的地移动到另一个目的地,然后我回击时,它会更新。我不确定我错过了什么或我做错了什么。

视图模型:

class ActivityViewModel : ViewModel() {
    var itemDataSourceFactory = OperationsDataSourceFactory()
        private set
    val livePagedList: LiveData<PagedList<Result<Operation?>>>

    init {
        val config = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setInitialLoadSizeHint(10)
            .setPageSize(10)
            .build()

        livePagedList = LivePagedListBuilder(itemDataSourceFactory, config).build()
    }

    fun refresh() {
        itemDataSourceFactory.dataSourceLiveData.value?.endCursor = null
        itemDataSourceFactory.refresh()
    }
}

数据源工厂:

class OperationsDataSourceFactory :
    DataSource.Factory<String, Result<Operation?>>() {
    val dataSourceLiveData = MutableLiveData<OperationsDataSource>()
    lateinit var dataSource: OperationsDataSource
    override fun create(): DataSource<String, Result<Operation?>> {
        dataSource = OperationsDataSource()
        dataSourceLiveData.postValue(dataSource)
        return dataSource
    }

    fun refresh(){
        dataSourceLiveData.value?.invalidate()
    }
}

而且,在片段上,我有这样的东西:

private fun initView() {
    binding.swipeToRefresh.setOnRefreshListener {
        itemViewModel.refresh()
    }
    getData() //observables with adapter.submitList(list)
}

【问题讨论】:

  • 嗨@Amg91。我可以看看 'OperationsDataSource' 你是如何实现的?

标签: android kotlin pagination android-jetpack swiperefreshlayout


【解决方案1】:

好的,经过长时间的研究,可能不是最好的解决方案,但开发人员也使用它。我们需要“无效”layoutManager 和适配器。

swipeToRefresh.setOnRefreshListener {
    operationsRecycler.apply {    
    layoutManager = null
    adapter = null
    layoutManager = LinearLayoutManager(
                        requireContext(),
                            LinearLayoutManager.VERTICAL,
                            false
                        )
    adapter = myAdapter
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多