我无法解决 getGroupView 方法的问题。
问题是侦听器 setOnCheckedChangeListener 被多次调用。
假设我检查了某个复选框项目。然后我将它滚动到视野之外,然后再滚动回来。发生的事情是再次调用了侦听器。问题是我将复选框 ID 存储在此侦听器内的数组列表中,以便稍后在代码中使用它。结果是每次调用侦听器时都会向数组列表添加更多元素并扭曲数据。
有针对这个的解决方法吗?我应该怎么办?例如,我应该注销监听器吗?
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = null;
final int group_position = groupPosition;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity_phrase, parent, false);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.groupTitle);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
checked.add((Integer) viewHolder.checkBox.getTag());
}
else {
checked.remove((Integer) viewHolder.checkBox.getTag());
}
}
});
view.setTag(viewHolder);
viewHolder.checkBox.setTag(groupPosition);
} else {
view = convertView;
((ViewHolder)view.getTag()).checkBox.setTag(groupPosition);
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(titles[groupPosition]);
for (int i = 0; i < checked.size(); i++) {
if (checked.get(i) == group_position) {
holder.checkBox.setChecked(true);
}
else if (checked.get(i) != group_position) {
holder.checkBox.setChecked(false);
}
}
return view;
}