在我的应用程序中,我想将 RecyclerView 用于另一个 Recyclerview,为此我编写了以下代码。我把我的申请结果放在下面的视频中:
https://www.youtube.com/shorts/YTgwfhnXob4
但是在滚动项目时运行应用程序后颜色混乱!
我有一个用于展示产品的 RecyclerView,在这个 RecyclerView 中我有另一个用于展示颜色的 RecyclerView!
搜索适配器代码:
class SearchAdapter @Inject constructor(@ApplicationContext private val context: Context) :
RecyclerView.Adapter<SearchAdapter.ViewHolder>() {
@Inject
lateinit var colorsAdapter: ColorsAdapter
private var items = emptyList<Data>()
private val decimalFormat by lazy { DecimalFormat("#.###") }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ItemSearchListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(items[position])
override fun getItemCount() = items.size
override fun getItemViewType(position: Int) = position
override fun getItemId(position: Int) = position.toLong()
inner class ViewHolder(private val binding: ItemSearchListBinding) : RecyclerView.ViewHolder(binding.root) {
@SuppressLint("SetTextI18n")
fun bind(item: Data) {
binding.apply {
//Texts
itemTitle.text = item.title
itemQuantity.text = "${context.getString(R.string.quantity)} ${item.quantity}" +
context.getString(R.string.item)
//Image
val image = "${IMAGE_BASE_URL}${item.image}"
itemImg.load(image) {
crossfade(true)
crossfade(300)
memoryCachePolicy(CachePolicy.ENABLED)
error(R.drawable.placeholder)
}
//Colors
item.colors?.let { colors ->
colorsAdapter.setData(colors)
binding.itemsColors.setupRecyclerview(
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, true),
colorsAdapter
)
}
}
}
}
fun setData(data: List<Data>) {
val adapterDiffUtils = BaseDiffUtils(items, data)
val diffUtils = DiffUtil.calculateDiff(adapterDiffUtils)
items = data
diffUtils.dispatchUpdatesTo(this)
}
}
颜色适配器代码:
class ColorsAdapter @Inject constructor() :
RecyclerView.Adapter<ColorsAdapter.ViewHolder>() {
private var items = emptyList<Data.Color>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ItemColorsListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(items[position])
override fun getItemCount() = items.size
override fun getItemViewType(position: Int) = position
override fun getItemId(position: Int) = position.toLong()
inner class ViewHolder(private val binding: ItemColorsListBinding) : RecyclerView.ViewHolder(binding.root) {
@SuppressLint("SetTextI18n")
fun bind(item: Data.Color) {
binding.apply {
itemsColor.setBackgroundColor(Color.parseColor(item.hexCode))
}
}
}
fun setData(data: List<Data.Color>) {
val adapterDiffUtils = BaseDiffUtils(items, data)
val diffUtils = DiffUtil.calculateDiff(adapterDiffUtils)
items = data
diffUtils.dispatchUpdatesTo(this)
}
}
我该如何解决这个问题?
我该如何解决这个问题?