![](/img/trans.png)
[英]How to properly load more items in a recyclerView, using Retrofit ? (kotlin)
[英]how can I No Rewrite items when load more in recyclerview kotlin?
社區。
我面臨一個問題,即某種程度的邏輯發現我被鎖定了
當我滾動時會帶來新數據,但是當您進入適配器時,這些項目會被重寫,而不是加入已經存在的項目。
在我的片段中:
private fun loadMoreProductList(root: View) {
val viewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
viewModel.setCurrentPage().observe(
viewLifecycleOwner,
{
if (it != null) {
postListAdapter.setListDataMore(it, type_data, this)
postListAdapter.notifyDataSetChanged()
notLoading = true
progressbarHome.visibility = View.GONE
}
})
viewModel.makeApiCallListPost(
root.context, _page.toString()
)
}
override fun getLoadMore() {
_page = _page + 1
type_data = 1
loadMoreProductList(View(context))
}
………………………………
在視圖模型中
var recyclerListPostList: MutableLiveData<List<PostData>> = MutableLiveData()
fun getRecyclerListPostObserver(): MutableLiveData<List<PostData>> {
return recyclerListPostList
}
fun setCurrentPage(): MutableLiveData<List<PostData>> {
recyclerListPostList.postValue(null)
return recyclerListPostList
}
fun makeApiCallListPost(context: Context, _page: String) {
val retroInstance = RetroInstance.getRetroInstance(context).create(
RetroService::class.java
)
val call = retroInstance.getPostData(
_page
)
call.enqueue(object : Callback<List<PostData>> {
override fun onResponse(call: Call<List<PostData>>, response: Response<List<PostData>>) {
if (response.isSuccessful) {
val destination = response.body()
destination?.let {
recyclerListPostList.postValue(response.body()!!)
}
} else {
recyclerListPostList.postValue(null)
}
}
override fun onFailure(call: Call<List<PostData>>, t: Throwable) {
t.printStackTrace()
recyclerListPostList.postValue(null)
}
})
}
在適配器中
fun setListData(
data: List<PostData>,
type_data: Int,
fragmentCallback: FragmentCallBack
) {
this.items0 = data as ArrayList<PostData>
this.fragmentCallback = fragmentCallback
}
fun setListDataMore(
data: List<PostData>,
type_data: Int,
fragmentCallback: FragmentCallBack
) {
items0.addAll(data as ArrayList<PostData>)
this.fragmentCallback = fragmentCallback
}
…………………………………………………………………………………………………………………………………………………… .....................
如果需要,我可以提供更多代碼
謝謝你。
重寫或綁定所有項目是因為您調用
postListAdapter.notifyDataSetChanged()
notifyDataSetChanged() 將刷新所有 ViewHolder
最簡單的解決方案就是改變
notifyDataSetChanged()
到notifyItemRangeChanged(startPosition, lastPosition(usually adapter size))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.