GridLayoutManager
当在分页库中LoadState
时,将跨度大小设置为 1 。Loading
我已经尝试过这个解决方案,但它不起作用。
对于复制问题:克隆这个官方 repo 并GridLayoutManager
设置SearchRepositoriesActivity
我的代码在这里
电影列表片段
....
private val adapter = MoviesAdapter()
....
private fun initAdapter() {
val decoration = DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
binding.rvMovies.addItemDecoration(decoration)
binding.rvMovies.layoutManager = GridLayoutManager(requireContext(), 2)
binding.rvMovies.isNestedScrollingEnabled = true
binding.rvMovies.adapter = adapter.withLoadStateFooter(
footer = MoviesLoadStateAdapter { adapter.retry() }
)
}
电影适配器
class MoviesAdapter(
) : PagingDataAdapter<Movie, MoviesAdapter.ViewHolder>(MOVIE_COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = ItemMovieListBinding.inflate(LayoutInflater.from(parent.context))
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val movie = getItem(position)
if (movie != null) {
val viewModel = MovieListItemViewModel(movie)
holder.bind(viewModel)
}
}
inner class ViewHolder(var viewBinding: ItemMovieListBinding) :
RecyclerView.ViewHolder(viewBinding.root) {
fun bind(viewModel: MovieListItemViewModel) {
viewBinding.viewModel = viewModel
}
}
companion object {
private val MOVIE_COMPARATOR = object : DiffUtil.ItemCallback<Movie>() {
override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean =
oldItem == newItem
}
}
}
MoviesLoadStateAdapter
class MoviesLoadStateAdapter(private val retry : () -> Unit) :
LoadStateAdapter<MoviesLoadStateAdapter.MoviesLoadStateViewHolder>()
{
override fun onBindViewHolder(holder: MoviesLoadStateViewHolder, loadState: LoadState) {
holder.bind(loadState)
}
override fun onCreateViewHolder(
parent: ViewGroup,
loadState: LoadState
): MoviesLoadStateViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_movie_load_state_footer_view, parent, false)
val binding = ItemMovieLoadStateFooterViewBinding.bind(view)
return MoviesLoadStateViewHolder(binding, retry)
}
inner class MoviesLoadStateViewHolder(private val binding: ItemMovieLoadStateFooterViewBinding,
retry : ()-> Unit) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.retryButton.setOnClickListener {
retry.invoke()
}
}
fun bind(loadState : LoadState){
if(loadState is LoadState.Error){
binding.errorMsg.text = loadState.error.localizedMessage
}
binding.progressBar.visibility = toVisibility(loadState is LoadState.Loading)
}
}
}
这里的目标ProgressBar
应该显示在屏幕中央。