问题描述:
使用paging3的过程中,本想通过为PagingDataAdaper添加页脚LoadStateAdapter方法onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState)中的loadState显示loading、error、no more,但是处理no more的时候发现loadState.endOfPaginationReached一直是false,且loadState只有LoadState.Loading、LoadState.Error两种状态
查看源码:
PagingDataAdapter.kt
fun withLoadStateFooter(
footer: LoadStateAdapter<*>
): MergeAdapter {
addLoadStateListener { loadStates ->
footer.loadState = loadStates.append
}
return MergeAdapter(this, footer)
}
LoadStateAdapter.kt
var loadState: LoadState = LoadState.NotLoading(endOfPaginationReached = false)
set(loadState) {
if (field != loadState) {
val oldItem = displayLoadStateAsItem(field)
val newItem = displayLoadStateAsItem(loadState)
if (oldItem && !newItem) {
notifyItemRemoved(0)
} else if (newItem && !oldItem) {
notifyItemInserted(0)
} else if (oldItem && newItem) {
notifyItemChanged(0)
}
field = loadState
}
}
/**
* Returns true if the LoadState should be displayed as a list item when active.
*
* By default, [LoadState.Loading] and [LoadState.Error] present as list items, others do not.
*/
open fun displayLoadStateAsItem(loadState: LoadState): Boolean {
return loadState is LoadState.Loading || loadState is LoadState.Error
}
通过查看源码可知,只有newItem为true才显示布局UI,若要newItem为true,则loadState的状态只有LoadState.Loading、LoadState.Error,故LoadStateAdapter只有loading、error两个状态。
解决方案:
监听PagingDataAdapter.addLoadStateListener可知,列表加载到底部会触发loadState.append的NotLoading(endOfPaginationReached=true)状态。
以上,想要通过loadState.endOfPaginationReached属性判断是否到底部,只有拿到loadState的NotLoading状态,通过重写displayLoadStateAsItem方法返回true即可。
override fun displayLoadStateAsItem(loadState: LoadState): Boolean {
return true
// return loadState is LoadState.Loading || loadState is LoadState.Error || loadState is LoadState.NotLoading
}
上面两种返回值效果一样,loadState的loading、error、notLoading三种状态都会触发。