AndroidのListView包含CheckBox时滑动丢失选中状态的解决
listview 中,如果有10项,其中手机屏幕显示1-6项,其余的7-10项在屏幕中不可见,得向下滚动后才能看到,这个时候,如果选中1、2项,再滚动到7-10项,之后再滚动回来1-6项,就发现1、2项并未被选中。
解决方法: 编写自定义的Adapter,一下是代码部分。、
class ListviewAdapter extends BaseAdapter { private ArrayList<Appinfo> lists; private ViewHolder viewHolder; private HashMap<Integer, Boolean> map; public ListviewAdapter(ArrayList<Appinfo> list) { lists = list; map = new HashMap<Integer, Boolean>(); for (int i = 0; i < lists.size(); i++) { map.put(i, false); } } @Override public int getCount() { return lists.size(); } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @SuppressLint("NewApi") @Override public View getView(final int position, View convertView, ViewGroup arg2) { final Appinfo appUnit = lists.get(position); if (convertView == null) { viewHolder = new ViewHolder(); convertView = LayoutInflater.from(SettingAppActivity.this) .inflate(R.layout.news_list_item, null); viewHolder.item_new = (TextView) convertView .findViewById(R.id.appName); viewHolder.item_pic = (ImageView) convertView .findViewById(R.id.icon); viewHolder.item_check = (CheckBox) convertView .findViewById(R.id.appcheck); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.item_new.setText(appUnit.getAppName()); viewHolder.item_pic.setBackground(appUnit.getAppIcon()); viewHolder.item_check .setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean checked) { Toast.makeText(SettingAppActivity.this, "checked=" + checked, 1000).show(); if (checked) { map.put(position, true); } else { map.put(position, false); } } }); viewHolder.item_check.setChecked(map.get(position)); return convertView; } } public class ViewHolder { public ImageView item_pic; public TextView item_new; public CheckBox item_check; }
正确的先存后取 之前错误的先取后存了
是因为index错误造成的,那么只要保证index值与当前positon保持一至即可,只要把添加监听器的方法加到初始化view中checkBox状态的代码之前即可.这样即始由于初始化造成调用了onCheckedChange()方法,也因为其中index值是最新的,不会错乱.