我正在使用第 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