为cardView设置不同的背景色,按照奇数和偶数的顺序

Set different background colors for cardView in order of odd and even

想为recyclerview 的奇数和偶数cardview 设置不同的背景颜色。在 Adapter class.

的 onBindViewHolder 方法中尝试

class NotificationAdapter(私有 val 通知:列表):RecyclerView.Adapter() {

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)
}

}

发现错误:“未解决的引用:它”

使用类似于:

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