【问题标题】:Change the color of the last item in a list view affecting the first item更改影响第一项的列表视图中最后一项的颜色
【发布时间】:2015-12-11 17:12:31
【问题描述】:

我正在尝试更改我的列表视图中最后一项的颜色,这很好,它正在工作,但是当我向后滚动列表视图的第一项也更改时,我不知道为什么会这样,这是我的代码:

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View vi = convertView;
        final ViewHolder holder;

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            vi = inflater.inflate(R.layout.list_row_user, null);
            holder = new ViewHolder();
            holder.title = (TextView) vi.findViewById(R.id.text1);
            holder.icon = (ImageView) vi.findViewById(R.id.icon);

            vi.setTag(holder);
        } else {
            holder = (ViewHolder) vi.getTag();
        }

        holder.title.setText(lista[position]);

        if (position == lista.length -1) {

            holder.icon.setVisibility(View.VISIBLE);
            holder.title.setTextColor(0xFF999999);
            holder.title.setPadding(0, 20, 0, 0);

        }

        return vi;
    }


    public class ViewHolder {
        TextView title;
        ImageView icon;

    }

【问题讨论】:

    标签: android listview android-listview android-arrayadapter baseadapter


    【解决方案1】:

    你必须像下面一样添加 else 部分

    if (position == lista.length -1) {
    
        holder.icon.setVisibility(View.VISIBLE);
        holder.title.setTextColor(0xFF999999);
        holder.title.setPadding(0, 20, 0, 0);
    
    }else{   
    
        holder.title.setTextColor(otherColor);
    }
    

    【讨论】:

    • 虽然正确,但可能需要解释。发生这种情况的原因是列表项被回收,即当您滚动列表时,相同的项目对象被重复使用(convertView != null 表示项目被重复使用)。这反过来意味着您不应依赖项目的任何默认属性,而应显式设置可能已被任何其他项目更改的所有属性。
    • 别忘了加上 notifyDataSetChanged();
    【解决方案2】:

    发生这种情况的原因是列表项被回收,即在您滚动列表时出于性能原因重复使用相同的项目对象(convertView != null 表示重新使用了先前膨胀和修饰的项目并传递给您重新装修)。

    这反过来意味着您不应依赖项目的任何默认属性,而应明确设置可能已被任何其他项目更改的所有属性,如@uday's answer 中所建议的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多