Paging3 RecyclerView Adapter
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.jarryleo:PagingAdapter:3.1.5'
}
//用作数据比较,执行RecyclerView条目动画,可以不实现方法,但是不建议这样做,性能差距就在这里体现
interface DifferData {
fun areItemsTheSame(d: DifferData): Boolean
fun areContentsTheSame(d: DifferData): Boolean
fun getChangePayload(d: DifferData): Any?
}
class NewsHolder : SimpleHolder<NewsBean.StoriesBean>(R.layout.item_news) {
override fun bindItem(
item: ItemHelper,
data: NewsBean.StoriesBean,
payloads: MutableList<Any>?
) {
item.binding<ItemNewsBinding>()?.data = data
}
}
recyclerView.adapter = SimplePagingAdapter(NewsHolder(), TitleHolder())
binding.adapter = binding.rvNews.buildAdapter {
addHolder(NewsHolder()) {
onItemClick {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it.data.url)))
}
onItemChildClick(R.id.iv_cover) {
toast(it.data.title)
}
}
addHolder(TitleHolder(), true) {
onItemClick {
toast(it.data.title)
}
}
addHolder(PlaceHolder())
setPager(model.pager)
}
//在ViewModel类里面实现
val pager = SimplePager<Long, DifferData>(viewModelScope) {
val date = it.key ?: initialKey
try {
//从网络获取数据
val data = api.getNews(date).await()
//返回数据
PagingSource.LoadResult.Page(data.stories, null, data.date?.toLongOrNull())
} catch (e: Exception) {
//请求失败
PagingSource.LoadResult.Error(e)
}
}
//绑定数据源
adapter.setPager(model.pager)
注意:不要使用adapter默认的 submitData,否则无法修改数据
使用就是这么方便,其中一些定义需要对paging3有一定了解,更多功能请看范例