我有一个使用BASEADAPTER的自定义列表视图 我创建了一个布尔值来维护复选框的状态。但每当我滚动列表视图时,复选框都会被取消选中。
public class DialogListSearchAdapter extends BaseAdapter {
private ArrayList<POJOInventoryStore> withList;
private boolean[] check;
public DialogListSearchAdapter(ArrayList<POJOInventoryStore> withList) {
this.withList = withList;
check = new boolean[withList.size()];
Arrays.fill(check, Boolean.FALSE);
}
@Override
public int getCount() {
return withList.size();
}
@Override
public Object getItem(int position) {
return withList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
parent.getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
vi = mInflater.inflate(R.layout.element_dialog_check, null);
holder = new ViewHolder();
holder.tvDialog = (TextView) vi.findViewById(R.id.textViewDialogCheck);
holder.cbDialog = (CheckBox) vi.findViewById(R.id.checkBoxDialogCheck);
holder.cbDialog.setTag(position);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.tvDialog.setText(withList.get(position).getName());
holder.cbDialog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
check[position] = Boolean.TRUE;
} else {
check[position] = Boolean.FALSE;
}
}
});
for (int i = 0; i < check.length; i++) {
if (check[i]==Boolean.TRUE) {
holder.cbDialog.setChecked(true);
} else {
holder.cbDialog.setChecked(false);
}
}
return vi;
}
private static class ViewHolder {
private TextView tvDialog;
private CheckBox cbDialog;
}
}
这里有什么问题?我错过了什么吗?
答案 0 :(得分:1)
你的问题是循环的最后一个问题。每一行都将获得最后一个checked []数组条目的状态。
如果你改变了最后一个的值,你应该看到。
PS:你的代码有点混乱&#34;并且可以进行优化:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
parent.getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
vi = mInflater.inflate(R.layout.element_dialog_check, null);
holder = new ViewHolder();
holder.tvDialog = (TextView) vi.findViewById(R.id.textViewDialogCheck);
holder.cbDialog = (CheckBox) vi.findViewById(R.id.checkBoxDialogCheck);
holder.cbDialog.setTag(position);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.tvDialog.setText(withList.get(position).getName());
holder.cbDialog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
check[position] = isChecked;
}
});
// This is the replacement of the for loop!
holder.cbDialog.setChecked(checked[position]);
return vi;
}