未显示分页 3 初始加载

问题描述 投票:0回答:5

我正在使用分页 3,除了初始加载状态之外,一切正常。我正在添加

withLoadStateFooter
但它在第一次调用时从不显示加载状态

这是我的实现

负载状态适配器

class LoadStateAdapter (
    private val retry: () -> Unit
): LoadStateAdapter<LoadStateViewHolder>() {

    override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) {
        holder.bindTo(loadState)
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        loadState: LoadState
    ): LoadStateViewHolder {
        return LoadStateViewHolder.create(parent, retry)
    }
}

加载状态视图支架

class LoadStateViewHolder(
    view : View,
    private val retryCallback: () -> Unit
) : RecyclerView.ViewHolder(view) {

    private val progressBar = view.findViewById<ProgressBar>(R.id.progress_bar)
    private val errorMsg = view.findViewById<TextView>(R.id.error_msg)
    private val btnRetry = view.findViewById<Button>(R.id.retry_button)
        .also {
            it.setOnClickListener { retryCallback() }
        }
    private var loadState : LoadState? = null

    companion object {
        fun create(parent: ViewGroup, retryCallback: () -> Unit): LoadStateViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.network_state_item, parent, false)
            return LoadStateViewHolder(
                view,
                retryCallback
            )
        }
    }


    fun bindTo(loadState: LoadState) {
        this.loadState = loadState

        btnRetry.isVisible = loadState !is LoadState.Loading
        errorMsg.isVisible = loadState !is LoadState.Loading
        progressBar.isVisible = loadState is LoadState.Loading

        if (loadState is LoadState.Error){
            errorMsg.text = loadState.error.localizedMessage
        }
    }
}

分页来源

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Model> {

    try {
        // Load page 1 if undefined.
        val currentPage = params.key ?: 0
        val offset = currentPage * 50

        val requestParams = hashMapOf<String, Any>()
        requestParams.put("limit", 50)
        requestParams.put("offset", offset)

        val response =  repository.getList(requestParams)
        val isFinish = response.paging != null && response.paging!!.next == null

        return LoadResult.Page(
            data = response.data ?: mutableListOf(),
            prevKey = null, // Only paging forward.
            nextKey = if (isFinish) null else currentPage + 1
        )
    } catch (e: Exception) {
        // Handle errors in this block
        return LoadResult.Error(e)
    }
}

查看模型

val listPagingFlow = Pager(PagingConfig(pageSize = 50)) {
    MyPagingSource(repository)
}.flow.cachedIn(viewModelScope)

活动

    val pagingAdapter = MyPagingAdapter()
    list.apply {
        setHasFixedSize(true)
        adapter = pagingAdapter.withLoadStateFooter(
            footer = LoadStateAdapter { pagingAdapter.retry() }
        )
    }

    lifecycleScope.launch(Dispatchers.IO) {
        viewModel.listPagingFlow.collectLatest { pagingData ->
            pagingAdapter.submitData(pagingData)
        }
    }

MyPagingAdapter 很简单

PagingDataAdapter

简而言之;加载状态工作正常,但在第一次请求时没有显示。有谁可以帮忙吗?

当前版本

3.0.0-alpha04

android paging android-paging android-paging-library
5个回答
13
投票

withLoadStateFooter
返回一个
ConcatAdapter
,它将原始
PagingDataAdapter
的结果与侦听
LoadStateAdapter
事件的
CombinedLoadState.append
连接起来。因此,预计它不会在初始加载期间返回项目(loadType ==
REFRESH
),并且它是这样设计的,因为在加载任何项目之前显示“页脚”实际上没有意义。

但是,要实现您想要的效果,您可以简单地创建自己的 ConcatAdapter,它非常接近地反映

.withLoadStateFooter
的实现:

val originalAdapter = MyPagingDataAdapter(...)
val footerLoadStateAdapter = MyFooterLoadStateAdapter(...)

addLoadStateListener { loadStates ->
    // You need to implement some logic here to update LoadStateAdapter.loadState
    // based on however you want to prioritize between REFRESH / APPEND load states.
    // Something really basic might be:
    // footerLoadStateAdapter.loadState = when {
    //     loadStates.refresh is NotLoading -> loadStates.append
    //     else -> loadStates.refresh
    // }
    footerLoadStateAdapter.loadState = ...
}
return ConcatAdapter(originalAdapter, footerLoadStateAdapter)

8
投票

使用页脚

LoadStateAdapter
显示初始加载会导致问题。如评论中所述,列表将自动滚动到底部。

解决此问题的方法是使用两个

LoadStateAdapter
,一个用于显示初始加载,第二个用于在加载更多项目时显示加载。

fun <T : Any, V : RecyclerView.ViewHolder> PagingDataAdapter<T, V>.withLoadStateAdapters(
    header: LoadStateAdapter<*>,
    footer: LoadStateAdapter<*>
): ConcatAdapter {
    addLoadStateListener { loadStates ->
        header.loadState = loadStates.refresh
        footer.loadState = loadStates.append
    }

    return ConcatAdapter(header, this, footer)
}

5
投票

我建议将初始加载和空状态从分页适配器中取出,并这样做:

adapter.loadStateFlow.collect {
    // to determine if we are done with the loading state, 
    // you should have already  shown your loading view elsewhere when the entering your fragment
    if (it.prepend is LoadState.NotLoading && it.prepend.endOfPaginationReached) {
        loading.visibility = View.GONE
    }
    if (it.append is LoadState.NotLoading && it.append.endOfPaginationReached) {
        emptyState.isVisible = adapter.itemCount < 1
    }
}

逻辑是

  • 如果追加已完成(it.append is LoadState.NotLoading && it.append.endOfPaginationReached == true),并且我们的适配器项目计数为零(adapter.itemCount < 1),则意味着没有任何内容可显示,因此我们显示空状态
  • 如果前置已完成(it.prepend is LoadState.NotLoading && it.prepend .endOfPaginationReached == true),那么我们已经完成了初始加载视图,我们应该隐藏它

1
投票

作为@dlam回答,您可以在适配器中使用自定义ConcatAdapter而不是withLoadStateFooter

fun withMySpecificFooter(
    footer: LoadStateAdapter<*>
): ConcatAdapter {
    addLoadStateListener { loadStates ->
        footer.loadState = when (loadStates.refresh) {
            is LoadState.NotLoading -> loadStates.append
            else -> loadStates.refresh
        }
    }
    return ConcatAdapter(this, footer)
}

0
投票

我将 CircularProgressIndicator 添加到我的布局中,并在请求数据时通过调用其 show() 方法来显示它,然后使用以下命令隐藏它:

lifecycleScope.launch {
    listAdapter.loadStateFlow.collect {
       if(it.refresh is LoadState.NotLoading) loadingIndicator.hide()
    }
 }

xml中的CircularProgressIndicator具有属性:visibility =“invisible”

© www.soinside.com 2019 - 2024. All rights reserved.