Android 高效适配器和文本格式

Android 高效适配器和文本格式,android,listactivity,Android,Listactivity,我正在使用扩展ListActivity的EfficientAdapter。 出于某种原因,当我使用以下代码时: public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.list_

我正在使用扩展ListActivity的EfficientAdapter。 出于某种原因,当我使用以下代码时:

  public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.text.setPadding((int) (Vars.screenWid-300), 30, 0, 30);
            if (position==1){
                holder.text.setPadding(20, 0, 20, 0);
                holder.text.setBackgroundColor(Color.DKGRAY);
            }else{
                holder.text.setPadding(20, 20, 20, 20);
                 holder.text.setBackgroundColor(Color.TRANSPARENT);
            }
        }
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.text.setText(String.valueOf(Vars.DATAMIN[position]));
        return convertView;
    }
我得到了列表,但不是只得到带有Color.DKGRAY的项目1,而是随机地在其他项目上得到它。我上下滚动,看到背景从一个项目到另一个项目的变化。 有什么想法吗?

视图是循环使用的(这意味着您正在设置视图的颜色,这些视图将显示在除1以外的其他位置),因此为了使其正常工作,您需要将代码移动到
convertView==null
块之外,在其中根据位置更改填充和颜色

if (convertView == null) {
    convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
    holder = new ViewHolder();
    holder.text = (TextView) convertView.findViewById(R.id.text);
    holder.text.setPadding((int) (Vars.screenWid-300), 30, 0, 30);
    convertView.setTag(holder);
} else {
    holder = (ViewHolder) convertView.getTag();
}
if (position==1){
    holder.text.setPadding(20, 0, 20, 0);
    holder.text.setBackgroundColor(Color.DKGRAY);
}else{
    holder.text.setPadding(20, 20, 20, 20);
    holder.text.setBackgroundColor(Color.TRANSPARENT);
}
holder.text.setText(String.valueOf(Vars.DATAMIN[position]));