我有一个带有ImageView,TextView和CheckBox的自定义ListViewAdapter。
当我选择特定的复选框并向下滚动时,向后滚动后,checkBox将被取消选中 我尝试了几个答案,但似乎没有任何效果。
这是我的代码:
public class ListViewAdapterDrawer extends ArrayAdapter<String> {
ImageView imageViewSensor;
TextView textViewSensor, textViewLogging;
CheckBox checkBoxSensor;
private boolean[] itemChecked;
int count;
public ListViewAdapterDrawer(Context context, String[] sensorArray) {
super(context, R.layout.adapter_listview_drawer, sensorArray);
itemChecked = new boolean[sensorArray.length];
for (int i = 0; i < this.getCount(); i++) {
itemChecked[i] = false;
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.adapter_listview_drawer, parent, false);
}
imageViewSensor = (ImageView) convertView.findViewById(R.id.imageViewSensor);
textViewSensor = (TextView) convertView.findViewById(R.id.textViewSensor);
checkBoxSensor = (CheckBox) convertView.findViewById(R.id.checkBoxSensor);
checkBoxSensor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBoxSensor.isChecked()){
itemChecked[position] = true;
}else {
itemChecked[position] = false;
}
}
});
checkBoxSensor.setChecked(itemChecked[position]);
return convertView;
}
}
答案 0 :(得分:2)
如果您阅读此link有关ListView如何被回收的信息,即回收机制,您应该能够理解为什么您的复选框未被选中。
This给出了关于ListView的相当详细的解释。
要点:
答案 1 :(得分:0)
尝试使用hashmap来维护checkbox的状态,因为当listview滚动时listview会回收相同的视图
HashMap<Integer, CoreQuestion.SubSection> selectionMap = new HashMap<>();
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.adapter_listview_drawer, parent, false);
}
imageViewSensor = (ImageView) convertView.findViewById(R.id.imageViewSensor);
textViewSensor = (TextView) convertView.findViewById(R.id.textViewSensor);
checkBoxSensor = (CheckBox) convertView.findViewById(R.id.checkBoxSensor);
checkBoxSensor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBoxSensor.isChecked()){
itemChecked[position] = true;
selectionMap.put(position,"true")
}else {
itemChecked[position] = false;
selectionMap.put(position,"false")
}
}
});
if(selectionMap.get(posotion)!=null)
{
checkBoxSensor.setChecked(itemChecked[position]);
}
return convertView;
}
}
可能会有所帮助。