如上图所示,当我刷新时,这些项目会被放错地方。
smartRefresh.setOnRefreshListener {
mViewModel.observeComposition(ConnectivityUtil.isNetworkReachable(this),mLabelId.toInt(),lifecycleScope).observe(this, Observer {
mCompositionAdapter.submitList(it)
smartRefresh.finishRefresh()
})
}
我的适配器
class CompositionsAdapter(context: Context) : PagedListAdapter<CompositionAbstract, CompositionsAdapter.ViewHolder>(CompositionAbstractDiffCallback()) {
private val mScreenWidth by lazy {
val displayMetrics = DisplayMetrics()
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getRealMetrics(displayMetrics)
displayMetrics.widthPixels
}
val width by lazy {
(mScreenWidth - 15.px * 3) / 2
}
val height by lazy {
val srcWidth = 165f.px
val srcHeight = 155f.px
width * (srcHeight / srcWidth)
}
class ViewHolder(private val binding: HomepageItemGroupCompositionBinding)
: RecyclerView.ViewHolder(binding.root) {
fun bind(item: CompositionAbstract) {
binding.apply {
composition = item.briefComposition
itemView.setOnClickListener {
ARouter.getInstance().build(HomePageArouterConstants.PATH_AUDIO_PLAYER).withString(HomePageArouterConstants.KEY_ID, item.briefComposition.id).navigation()
}
executePendingBindings()
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = HomepageItemGroupCompositionBinding.inflate(LayoutInflater.from(parent.context))
binding.imageView.layoutParams = LinearLayout.LayoutParams(width, height.toInt())
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
getItem(position)?.let {
holder.bind(it)
}
}
}
我的物品装饰
class GridSpacingItemDecoration(private val spanCount: Int,
private val verticalSpacing: Int,
private val topSpacing: Int
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
val position = parent.getChildAdapterPosition(view)
if (position / spanCount == 0) {
outRect.top = topSpacing
}
if (position % spanCount == 1) {
outRect.left = 7.px
}
outRect.bottom = verticalSpacing
}
}
我的差异
class CompositionAbstractDiffCallback : DiffUtil.ItemCallback<CompositionAbstract>() {
override fun areItemsTheSame(oldItem: CompositionAbstract, newItem: CompositionAbstract): Boolean {
return oldItem.briefComposition.id == newItem.briefComposition.id
}
override fun areContentsTheSame(oldItem: CompositionAbstract, newItem: CompositionAbstract): Boolean {
return oldItem == newItem
}
}
对这个问题有什么想法吗?先谢谢了!