我试图使一个回收器视图加载更多的数据,因为用户向下滚动而不删除前一个单元格。例子:(Instagram, twitter…)
当我向下滚动时,在所有回收器视图单元格中获取新数据前一个和新单元格。
如果我有10个单元格,然后向下滚动,它会得到另一个新的10但是现在所有的20个都是一样的,前10个被替换了
主片段
photosList.layoutManager = mLayoutManager
viewModel.refresh()
photosList.apply {
layoutManager = LinearLayoutManager(context)
adapter = photosAdapter
}
observeViewModel()
photosList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy > 0) { //check for scroll down
//visibleItemCount = mLayoutManager.childCount
var layoutManager = photosList.layoutManager as LinearLayoutManager
visibleItemCount =
layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition() + 1
totalItemCount = layoutManager.itemCount
pastVisibleItems = layoutManager.findFirstVisibleItemPosition()
if (loading) {
if (visibleItemCount + pastVisibleItems >= totalItemCount) {
loading = false
// Fetch new data
viewModel.fetchMorePhotos()
observeViewModelGetMore()
loading = true
}
}
}
}
})
ViewModel
fun fetchMorePhotos() {
pageNumber += 1
fetchPhotos()
}
private fun fetchPhotos() {
loading.value = true
//loading2.value = true
disposable.add(
PhotosService.getPhotos(pageNumber)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<List<PhotoData>>() {
override fun onSuccess(value: List<PhotoData>?) {
Photos.value = value!!
PhotoLoadError.value = false
loading.value = false
//loading2.value = false
}
override fun onError(e: Throwable?) {
PhotoLoadError.value = true
loading.value = false
//loading2.value = false
}
})
)
}
适配器
class PhotoListAdapter(
var photos: ArrayList<PhotoData>,
private var click_listener: OnPhotoItemClickListner
) :
RecyclerView.Adapter<PhotoListAdapter.PhotoViewHolder>() {
fun updatePhotos(newPhotos: List<PhotoData>) {
photos.clear()
photos.addAll(newPhotos)
notifyDataSetChanged()
}
fun getMorePhotos(newPhotos: List<PhotoData>) {
val position: Int = photos.size + 1
photos.addAll(newPhotos)
notifyItemChanged(position,newPhotos)
}
无限滚动是一个复杂的话题,我不会试图自己解决。你需要使用Android分页库:
https://proandroiddev.com/infinite-scrolling-with-android-paging-library-and-flow-api-e017f47517d6