kotlin 按奇偶顺序为cardView设置不同的背景色

gzszwxb4  于 2023-01-09  发布在  Kotlin
关注(0)|答案(2)|浏览(117)

想为循环视图的奇数和偶数卡片视图设置不同的背景颜色。尝试使用Adapter类的onBindViewHolder方法。
类NotificationAdapter(私有瓦尔通知:列表):回收器视图适配器<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)
}

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

xu3bshqb

xu3bshqb1#

使用类似于:

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

xmd2e60i

xmd2e60i2#

试试这个:

if(position.isEven){
         .setCardBackgroundColor(
                        ContextCompat.getColor(holder.itemView.context, R.color.red)}
     else{
        .setCardBackgroundColor(
                        ContextCompat.getColor(holder.itemView.context, R.color.green)
       }

如果有人仍然得到白色,而不是他选择的颜色,只是改变模拟器你的工作,这是为我工作

相关问题