我有一个用于列表视图的自定义适配器。列表视图有一个复选框,但是当我向下滚动然后向上滚动时,复选框不会保持选中状态。我有一个模型,模型中有一个"选定"的布尔值。这是我的适配器,谁能告诉我我做错了什么?我已经尝试了多次,但似乎没有任何效果。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_row_friends, null);
CheckBox friend_checkbox = (CheckBox)row.findViewById(R.id.friends_checkbox);
if(data.get(position).selected) {
friend_checkbox.setChecked(true);
} else {
friend_checkbox.setChecked(false);
}
}
CheckBox friend_checkbox = (CheckBox)row.findViewById(R.id.friends_checkbox);
friend_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.get(position).setSelected(isChecked);
Log.d("FriendAdapter", data.get(position).selected + "");
}
});
正如Raghunandan所建议的那样,发生这种情况是因为ListView回收视图,因此convertView在大多数时候可能不为空。试试这个:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_row_friends, null);
}
CheckBox friend_checkbox = (CheckBox)row.findViewById(R.id.friends_checkbox);
friend_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.get(position).setSelected(isChecked);
Log.d("FriendAdapter", data.get(position).selected + "");
}
});
if(data.get(position).selected) {
friend_checkbox.setChecked(true);
} else {
friend_checkbox.setChecked(false);
}
}