我用自定义适配器制作了一个列表视图。它有一个 Imageview、textview 和一个复选框
---------------------------------------
<ImageView --- textView --- checkbox >
---------------------------------------
我正在使用名为“mCheckStates”的 SparseBooleanArray 来跟踪复选框的状态。另外我想限制用户一次只检查两个复选框。为此,我使用了一个 int 变量作为计数器。
但是当我滚动 listView onCheckChangedListener 被调用并且计数减少一,有时减少二,允许用户检查 3 或 4 个复选框。
我怎样才能阻止这种情况发生?请帮我找到解决方案。谢谢。
代码
protected class MyCustomAdapter extends ArrayAdapter<String> implements
CompoundButton.OnCheckedChangeListener {
ArrayList<String> myList;
int count = 0;
ViewHolder holder = null;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<String> sList) {
super(context, textViewResourceId, sList);
mCheckStates = new SparseBooleanArray(sList.size());
myList = sList;
}
private SparseBooleanArray mCheckStates;
private class ViewHolder {
TextView text;
CheckBox chkbox;
ImageView imageview;
}
@Override
public int getCount() {
return stg1.size();
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.new_search_adptr, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.adapterText1);
holder.chkbox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
holder.imageview = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.chkbox.setTag(position);
holder.chkbox.setChecked(mCheckStates.get(position, false));
holder.chkbox.setOnCheckedChangeListener(this);
holder.text.setText(stg1.get(position).toString());
holder.imageview.setImageBitmap(arr_img.get(position));
return convertView;
}
public boolean isChecked(int position) {
System.out.println("inside isChecked");
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
System.out.println("inside setChecked");
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
System.out.println("inside toggle");
setChecked(position, !isChecked(position));
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("\n inside onCheckedChanged: " + isChecked);
if (isChecked) {
System.out.println("inside isChecked true");
System.out.println("count= " + count);
if (count >= 2) {
// count--;
System.out.println("inside count>2: " + count);
buttonView.setChecked(false);
Toast.makeText(getApplicationContext(),
"Please select only two cars!", Toast.LENGTH_LONG)
.show();
} else {
count++;
System.out.println("inside else: " + count);
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
} else {
System.out.println("inside isChecked false" + count);
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
count--;
}
}
}