要实现Android分页3.0,你需要使用RecyclerView和Paging Library。以下是一个简单的代码示例来实现Android分页3.0:
dependencies {
implementation 'androidx.paging:paging-runtime:3.0.0'
}
class MyPagingSource : PagingSource() {
override suspend fun load(params: LoadParams): LoadResult {
try {
val nextPage = params.key ?: 1
val response = apiService.getItems(nextPage)
val items = response.items
val prevPage = if (nextPage == 1) null else nextPage - 1
val nextPage = if (items.isNotEmpty()) nextPage + 1 else null
return LoadResult.Page(
data = items,
prevKey = prevPage,
nextKey = nextPage
)
} catch (e: Exception) {
return LoadResult.Error(e)
}
}
}
class MyAdapter : PagingDataAdapter- (diffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item)
}
companion object {
private val diffCallback = object : DiffUtil.ItemCallback
- () {
override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem == newItem
}
}
}
}
class MainActivity : AppCompatActivity() {
private val viewModel by viewModels()
private val adapter = MyAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById(R.id.recycler_view)
recyclerView.adapter = adapter
lifecycleScope.launch {
viewModel.pagingDataFlow.collectLatest { pagingData ->
adapter.submitData(pagingData)
}
}
}
}
class MainViewModel : ViewModel() {
private val repository = MyRepository()
val pagingDataFlow: Flow> = Pager(PagingConfig(pageSize = 20)) {
MyPagingSource()
}.flow.cachedIn(viewModelScope)
}
这样,你就实现了Android分页3.0。当RecyclerView滚动到底部时,Paging Library会自动加载下一页数据,并在RecyclerView中显示。