android - 按奇偶顺序为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)
}
}
发现错误:“未解决的参考:它”
解决方案
使用类似的东西:
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
.
推荐阅读
- vb.net - VB.net - 表格不会显示
- javascript - 使用所选输入的 innerhtml 更改项目类别
- angular - 在订阅时处理 forkJoin 中的错误
- outlook - Outlook 不直接显示约会
- javascript - 使用 CSS 和 JS 以时间间隔显示文本
- python - 如何始终在 Spyder 项目中运行主文件
- vue.js - 将 nuxt.js 应用程序配置为在网络服务器上的子目录中工作
- react-native - React Native FlatList 可触摸不透明度
- java - 无法初始化类 com.fasterxml.jackson.databind.ObjectMapper
- excel - IF 语句的单元格中可以包含通配符吗?