You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中修改RecyclerView列表项的背景颜色

RecyclerView列表项背景修改不生效问题排查方案

已知代码问题修正

你提供的Adapter代码存在结构错误:setOnLongClickListener 代码块写在了ViewHolder的init初始化块外部,这部分代码不会被执行,需移入init块内部,修正后代码如下:

inner class ExampleViewHolder(itemView:View): RecyclerView.ViewHolder(itemView) {
    val tv_ID: TextView = itemView.tv_ID
    val tv_NAME: TextView = itemView.tv_NAME
    
    init {
        itemView.setOnClickListener{
            onItemClick?.invoke(exampleList[absoluteAdapterPosition], absoluteAdapterPosition)
            notifyItemChanged(selected_item)
            selected_item = absoluteAdapterPosition
            notifyItemChanged(selected_item)                
        }
        // 长按监听移入init块内
        itemView.setOnLongClickListener {
            onItemLongClick?.invoke(exampleList[absoluteAdapterPosition])
            true
        }
    }
}

另外点击事件中冗余的itemView.setSelected(true)可以删除,你当前使用代码动态设置背景,该配置不会生效。

背景不生效常见原因及解决方案

  • item布局层级遮挡
    检查R.layout.item_recy的根布局(ConstraintLayout)是否设置了background/backgroundTint属性,若有先移除;同时确认根布局内的子控件(如TextView)没有设置不透明背景,遮挡了根布局的背景色。可临时给根布局添加10dp的padding,点击时观察padding区域是否变色,若变色即可确定是子控件遮挡问题。
  • 布局嵌套冲突
    ScrollView嵌套RecyclerView会触发滚动冲突,导致item复用异常、刷新不生效:
    1. 优先将ScrollView替换为NestedScrollView
    2. 给RecyclerView添加属性android:nestedScrollingEnabled="false"关闭嵌套滚动
    3. 确认TableLayout内的RecyclerView高度不要设置为wrap_content,要么设为固定值,要么设为match_parent,避免RecyclerView一次性加载全部item导致复用逻辑失效
  • 逻辑执行验证
    在onBindViewHolder的背景判断逻辑中添加日志打印,确认点击后selected_item的值是否正常更新,背景设置代码是否被执行。

内容的提问来源于stack exchange,提问作者jenik2205

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:27:05