ListView上下滚动时行颜色异常变更问题求助
解决ListView滚动时行背景色异常变更的问题
这个问题的核心原因是ListView的View复用机制导致的:当你滚动列表时,之前已经设置过背景色的convertView会被重新分配给新的列表项,但你只在Active为1或2时设置了背景色,没有处理其他情况,也没有重置默认的背景色,所以旧的颜色会残留到新的列表项上,造成颜色乱跳的问题。
修复方案
我们需要确保每一个列表项在复用View时,都明确设置对应的背景色(包括默认状态),而不是只处理部分情况。另外,直接使用数据源里的Active字段比读取TextView的文本更高效,也能避免文本转换可能带来的错误。
修改后的GetView方法代码如下:
public override View GetView(int position, View convertView, ViewGroup parent) { DataViewHolder holder = null; if (convertView == null) { convertView = LayoutInflater.From(mContext).Inflate(Resource.Layout.FactAdapter, null, false); holder = new DataViewHolder(); holder.txtid = convertView.FindViewById<TextView>(Resource.Id.idtxt); holder.txtName = convertView.FindViewById<TextView>(Resource.Id.Nametxt); holder.txtPhone = convertView.FindViewById<TextView>(Resource.Id.Phonetxt); holder.txtActive = convertView.FindViewById<TextView>(Resource.Id.Activetxt); convertView.Tag = holder; } else { holder = convertView.Tag as DataViewHolder; } // 获取当前项的实体数据 var currentItem = mitems[position]; holder.txtid.Text = currentItem.id.ToString(); holder.txtName.Text = currentItem.Name; holder.txtPhone.Text = currentItem.Phone; holder.txtActive.Text = currentItem.Active.ToString(); // 根据Active值设置背景色,覆盖所有情况 switch(currentItem.Active) { case 1: holder.txtName.SetBackgroundColor(Color.LightGreen); holder.txtPhone.SetBackgroundColor(Color.LightGreen); break; case 2: holder.txtName.SetBackgroundColor(Color.Orange); holder.txtPhone.SetBackgroundColor(Color.Orange); break; default: // 重置为默认背景色,比如原来的白色或者布局里设置的背景 holder.txtName.SetBackgroundColor(Color.White); holder.txtPhone.SetBackgroundColor(Color.White); break; } return convertView; }
关键改动点说明
- 直接使用数据源的Active字段:避免通过
holder.txtActive.Text读取值,减少字符串转换的开销,也避免TextView文本可能被修改导致的判断错误。 - 覆盖所有情况的背景设置:通过
switch-case处理了Active为1、2和其他值的所有场景,在default分支里重置为默认背景色,确保复用的View不会残留之前的颜色。 - 清晰的逻辑分支:相比多个独立的
if判断,switch-case让逻辑更清晰,也更容易维护。
如果你的列表项布局里原本有默认的背景色,也可以用Resource.Color.xxx来引用资源文件里的颜色,而不是硬编码Color.White,这样更符合Android的资源管理规范。
内容的提问来源于stack exchange,提问作者Dim Chris
相关产品推荐
相关产品推荐

