首页 > 解决方案 > 按奇偶顺序为cardView设置不同的背景颜色

问题描述

想为recyclerview的奇偶cardview设置不同的背景颜色。尝试使用 Adapter 类的 onBindViewHolder 方法。

类 NotificationAdapter(私有 val 通知:列表):RecyclerView.Adapter<NotificationAdapter.NotificationViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotificationViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val view = inflater.inflate(R.layout.card_notification, parent, false)
    return NotificationViewHolder(view)
}

override fun onBindViewHolder(holder: NotificationViewHolder, position: Int) {
    holder.txtTitle.text = notifications[position]

    if(position.isEven)
        it.root.setBackgroundColor(context.colorRes(R.color.sponsor_even_color))
    else
        it.root.setBackgroundColor(context.colorRes(R.color.sponsor_odd_color))

}

override fun getItemCount(): Int {
    return notifications.size
}

class NotificationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    var txtTitle: TextView = itemView.findViewById(R.id.tv_notification_title)
    var txtDescription: TextView = itemView.findViewById(R.id.tv_notification_description)
}

}

发现错误:“未解决的参考:它”

标签: androidkotlinandroid-recyclerviewandroid-cardview

解决方案


使用类似的东西:

class NotificationViewHolder(...){
   var cardView: CardView = = itemView.findViewById(R.id.cardView)
   //....
}

override fun onBindViewHolder(holder: NotificationViewHolder, position: Int) {
    holder.txtTitle.text = notifications[position]

    if(position.isEven)
       holder.cardView.setCardBackgroundColor(....)
    else
       holder.cardView.setCardBackgroundColor(....)
}

并使用方法setCardBackgroundColor代替setBackgroundColor.


推荐阅读