我有一个带有复选框的列表视图。我单击特定项目,相应的复选框被选中,但它也会在列表视图中每 8-10 行后重复选择复选框。我理解这是因为在 android 中,仅存储可见屏幕的视图以进行内存优化。但我一直无法克服这种情况。请建议。
public class FBFriendsListAdaptor extends ArrayAdapter<FBFriendItem>{
private final Context context;
private static List<FBFriendItem> items;
private SparseArray<FBFriendItem> checkedItems = new SparseArray<FBFriendItem>();
ViewHolder holder;
public FBFriendsListAdaptor(Context context, List<FBFriendItem> items) {
super(context, R.layout.fb_friend_list, items);
this.items = items;
this.context = context;
}
@Override
public FBFriendItem getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.fb_friend_list, parent, false);
}
holder = new ViewHolder();
holder.selectFriendCB = (CheckBox)v.findViewById(R.id.selectFriendCB);
v.setTag(holder);
v.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if (checkedItems.get(position) != null){
checkedItems.remove(position);
holder.selectFriendCB.setChecked(false);
}
else {
checkedItems.put(position, items.get(position));
holder.selectFriendCB.setChecked(true);
}
}
});
FBFriendItem item = items.get(position);
TextView firstNameTV = (TextView) v.findViewById(R.id.firstNameTV);
TextView lastNameTV = (TextView) v.findViewById(R.id.lastNameTV);
ImageView picIV = (ImageView) v.findViewById(R.id.picIV);
if (!item.getFbId().isEmpty()) {
firstNameTV.setText(" " + item.getFirstName());
lastNameTV.setText(" " + item.getLastName());
Bitmap image = item.getImage();
if(image != null) {
picIV.setImageBitmap(image);
}
}
return v;
}
public SparseArray<FBFriendItem> getCheckedItems(){
return checkedItems;
}
static class ViewHolder {
CheckBox selectFriendCB;
}
}