由于在NestedScrollView 中使用了RecyclerView,我遇到了同样的问题。
如果您处于同样的情况,请尝试删除 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 传递给 PagingSource 类中的 nextKey
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)
}
}