更新ListView中的ImageView

时间:2012-09-19 19:22:12

标签: android listview caching adapter

我坚持了几个小时,我正在尝试为ListView中的第一个列表项设置图像,但其他列表项上的一些ImageView也在变化。

public class MyAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    public ArrayList<ListItem> myItems = new ArrayList<ListItem>();

    Player[] players;

    public MyAdapter() {
        DataBase banco = new DataBase(ScoreBoard.this);
        players = banco.consultaJogadores(); 
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        for (int i = 0; players[i] != null; i++) {
            ListItem listItem = new ListItem();
            listItem.caption = players[i].getName();
            myItems.add(listItem);
        }
        notifyDataSetChanged();
    }

    public int getCount() {
        return myItems.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.topplayer, null);      
            holder.textView = (TextView) convertView.findViewById(R.id.topPlayerTextView);
            holder.imageview = (ImageView) convertView.findViewById(R.id.topPlayerImageView);   
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }           
        holder.textView.setText(position + " " + players[position].getName() + " " + players[position].getScore());
        if (position == 0) {
            holder.imageview.setImageResource(R.drawable.ball);
        }
        return convertView;
    }
}

class ViewHolder {
    TextView textView;
    ImageView imageview;
}

class ListItem {
    String caption;
}

我想改变名单上第一个玩家的图像。 索引0,1,4,6,8,9,11,13和14的玩家得到更新,它不遵循逻辑顺序。 当我滚动时,图像会再次变化。

感谢

1 个答案:

答案 0 :(得分:3)

您正在回收视图,因此当您不希望设置listitems图像时,您必须明确地取消它:

if (position == 0) {
    holder.imageview.setImageResource(R.drawable.ball);
} else {
    holder.imageview.setImageDrawable(null);
}

(否则它只会记住上一次使用该视图((即convertView))时设置的图像!