gpt4 book ai didi

android - Jetpack 分页库无需滚动即可加载所有页面

转载 作者:行者123 更新时间:2023-12-04 04:09:29 24 4
gpt4 key购买 nike

我正在使用 PageKeyedDataSource 从网络获取数据。数据共有 6 页,pagesize 为 10。

val myPagingConfig = PagedList.Config.Builder()
.setPageSize(pageSize)
.setPrefetchDistance(pageSize)
.setInitialLoadSizeHint(pageSize)
.setEnablePlaceholders(false)
.build()

但是分页会在加载后触发 5 次,无需滚动。然后将加载整个数据

最佳答案

由于使用 RecyclerView,我遇到了同样的问题在 NestedScrollView .
如果您遇到同样的情况,请尝试删除 NestedScrollView或使用 this而不是 NestedScrollView。
(引用这篇 answer )

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.core.view.forEach
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

open class SmartNestedScrollView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : NestedScrollView(context, attrs, defStyleAttr) {

override fun measureChildWithMargins(child: View, parentWidthMeasureSpec: Int, widthUsed: Int, parentHeightMeasureSpec: Int, heightUsed: Int) {
if (findNestedRecyclerView(child) != null) {
val lp = child.layoutParams as MarginLayoutParams
val childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
lp.topMargin + lp.bottomMargin, MeasureSpec.AT_MOST
)
child.measure(parentWidthMeasureSpec, childHeightMeasureSpec)
} else {
super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed)
}
}

private fun findNestedRecyclerView(view: View): RecyclerView? {
if (view is RecyclerView) {
val vertical = (view.layoutManager as? LinearLayoutManager)?.orientation == LinearLayoutManager.VERTICAL
if (vertical) return view
}

if (view is ViewGroup) {
view.forEach { child ->
val rv = findNestedRecyclerView(child)
if (rv != null) return rv
}
}

return null
}
}
//reference: https://gist.github.com/danaimset/abacaa50d746a4537686a08ecc33c1a9
更新:
确保将 null 传递给 nextKeyPagingSource如果到达数据末尾则分类(即没有更多数据要加载)
override suspend fun load(params: LoadParams<String>): LoadResult<String, Wallpost> {

return try {
val nextPage = params.key ?: url
val response = repository.getPostList(nextPage)

LoadResult.Page(
data = response.list,
prevKey = "",
nextKey = if (response.hasNextPage) response.next else null
)
}catch (e: Exception){
LoadResult.Error(e)
}
}

关于android - Jetpack 分页库无需滚动即可加载所有页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61998881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com