【问题标题】:Set different background colors for cardView in order of odd and even按奇偶顺序为cardView设置不同的背景颜色
【发布时间】:2021-06-23 00:51:14
【问题描述】:

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

class NotificationAdapter(private val notifications: List) : 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)
}

}

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

【问题讨论】:

  • 问题是什么?
  • 未解决的参考:它
  • 发现这个错误 --> 未解决的参考:它
  • 尝试将it.root更改为holder

标签: android kotlin android-recyclerview android-cardview


【解决方案1】:

使用类似的东西:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2021-08-26
    • 2019-07-27
    • 2020-07-21
    • 2021-12-31
    相关资源
    最近更新 更多