解决Checkbox滑动错乱问题

我自己找了很多的解决滑动错乱的问题,我发现好多都是用的map来保存的状态,所以想了个其他的方法进行操作。总体来说非常的简单,自己看看代码就明白了

public class MainActivity extends Activity {
private ListView mlv;
private MyListViewAdapter mAdapter;
private ArrayListlist;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        list = new ArrayList();
        //模拟从网络获取数据
        for(int i=0;i<24;i++){
        Bean bean  = new Bean();
        bean.name="item"+i;
        bean.isChecked=false;
        list.add(bean);
        }
        mAdapter = new MyListViewAdapter(MainActivity.this, list);
        mlv.setAdapter(mAdapter);
        //到这里就一切OK了!!!
        mlv.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(AdapterView parentView, View view, int position,
long arg3) {
boolean isChecked= list.get(position).isChecked;
list.get(position).isChecked=!isChecked;
mAdapter.notifyDataSetChanged();
}
});
    }
    private void initView(){
    mlv=(ListView) findViewById(R.id.listView1);
    }
}


配置的adapter

public class MyListViewAdapter extends BaseAdapter {
private Context mContext;
private ListmList;
private ViewHolder holder;
public MyListViewAdapter(Context context , Listlist){
this.mContext=context;
this.mList=list;
}


@Override
public int getCount() {
return mList.size();
}


@Override
public Object getItem(int position) {
return mList.get(position);
}


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


@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null) {
holder=new ViewHolder();
convertView=LayoutInflater.from(mContext).inflate(R.layout.item_custom_cb, null);
holder.mCB=(CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}else{
holder=(ViewHolder) convertView.getTag();
}
//每次显示item的时候首先对选中状态进行判断
if (mList.get(position).isChecked) {
holder.mCB.setChecked(true);
}else{
holder.mCB.setChecked(false);
}
holder.mCB.setText(mList.get(position).name);
return convertView;
}
public static class ViewHolder{
CheckBox mCB;
}
}

自定义的bean

public class Bean {
//isChecked:在后台解析的基础上添加一个字段,用来做是否选中的判断
public boolean isChecked;
public String name;
}

你可能感兴趣的:(解决Checkbox滑动错乱问题)