ListView的bug解决,如果有checkbox的话,选中的值在翻屏时会跳来跳去

始化数据
data = new ArrayList<HashMap>();  
for (int i = 0; i < 20; i++) {  
    map = new HashMap();  
    map.put("title", "title-->" + i);  
    map.put("content", "content--" + i);  
    data.add(map);  
}  
设置ListView
adapter = new MyAdapter(CheckList.this, data);  
mListView.setAdapter(adapter);  
// 为listview的子项添加点击事件,position就是原来的arg2   
mListView.setOnItemClickListener(new OnItemClickListener() {  
    @Override  
    public void onItemClick(AdapterView<?> parent, View view,  
            int position, long id) {  
        System.out.println("您所点击的行号是:" + position);  
    }  
});  
定义我们需要的adapter
int count = scroll_num;  
Context mContext;  
ArrayList<HashMap> mData;  
LayoutInflater mInflater;  
  
public MyAdapter(Context context, ArrayList<HashMap> data) {  
    this.mContext = context;  
    this.mData = data;  
    mInflater = (LayoutInflater) mContext  
            .getSystemService(mContext.LAYOUT_INFLATER_SERVICE);  
    if (count > mData.size()) {  
        count = mData.size();  
    }  
    isSelected = new HashMap<Integer, Boolean>();  
    for (int i = 0; i < data.size(); i++) {  
        isSelected.put(i, false);  
    }  
}  
  
@Override  
public int getCount() {  
    return mData.size();  
}  
  
@Override  
public Object getItem(int position) {  
    return position;  
}  
  
@Override  
public long getItemId(int position) {  
    return position;  
}  
  
@Override  
public View getView(final int position, View convertView,  
        ViewGroup parent) {  
    if (convertView == null) {  
        convertView = mInflater.inflate(R.layout.item_listview, null);  
        holder = new ViewHolder();  
        holder.content = (TextView) convertView  
                .findViewById(R.id.item_listview_content);  
        holder.checkBox = (CheckBox) convertView  
                .findViewById(R.id.item_listview_checkbox);  
        convertView.setTag(holder);  
    } else {  
        holder = (ViewHolder) convertView.getTag();  
    }  
  
    holder.content  
            .setText(data.get(position).get("content").toString());  
    holder.checkBox.setChecked(isSelected.get(position));  
    holder.checkBox.setOnClickListener(new OnClickListener() {  
        @Override  
        public void onClick(View v) {  
            if (isSelected.get(position)) {  
                isSelected.put(position, false);  
            } else {  
                isSelected.put(position, true);  
            }  
            notifyDataSetChanged();  
        }  
    });  
  
    return convertView;  
}  
最后再定义一个xml的adapter



你可能感兴趣的:(object,list,ListView,ITeye,Class)