现象:listview 中,如果有10项,其中手机屏幕显示1-6项,其余的7-10项在屏幕中不可见,得向下滚动后才能看到,这个时候,如果选中1、2项,再滚动到7-10项,之后再滚动回来1-6项,就发现1、2项并未被选中。
解决方法: 编写自定义的Adapter
- public class TestAdapter extends ArrayAdapter<String> {
- private int resource;
- private LayoutInflater inflater;
- private boolean[] checks; //用于保存checkBox的选择状态
- public TestAdapter(Context context, int resource, List<String> list) {
- super(context, resource, list);
- checks = new boolean[list.size()];
- this.resource = resource;
- inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- ViewHolder holder = null;
- if(convertView == null){
- convertView = inflater.inflate(resource, null);
- holder = new ViewHolder();
- holder.title = (TextView) convertView.findViewById(R.id.title);
- holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
- convertView.setTag(holder);
- }else {
- holder = (ViewHolder) convertView.getTag();
- }
- holder.title.setText(getItem(position));
- final int pos = position; //pos必须声明为final
- holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
- @Override
- public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
- checks[pos] = isChecked;
- }});
- holder.checkBox.setChecked(checks[pos]);
- return convertView;
- }
- static class ViewHolder {
- TextView title;
- CheckBox checkBox;
- }
- }