我有一个带复选框的 ListView:
Oncheckedchanged(..)
当用户选中/取消选中列表视图上的项目时调用OncheckedChanged(..)
当用户单击列表项时再次调用onItemClick(.....)
这是一个已知的问题?如何区分事件。
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
viewHolder.imageview= (ImageView) convertView.findViewById(R.id.imageView1);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.check, viewHolder.checkbox);
convertView.setTag(R.id.imageView1, viewHolder.imageview);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.imageview.setTag(position);
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
// change the default-image here
if(list.get(position).getcontact_id()==5)
{
viewHolder.imageview.setImageResource(android.R.drawable.ic_dialog_map);
}...
..
return convertView;
}
编辑
onCheckedChanged() 被调用
- 当没有选择任何项目并且用户单击复选框时
- 如果列表包含 3 个项目并且当用户单击任何其他项目时,将调用 onItemclick() 并触发 onCheckedChanged() 3 次(=no: of items in the listview)