I have a ListView with checkbox:
Oncheckedchanged(..)
is called when user check/uncheck item on listviewOncheckedChanged(..)
called again when user click the listitem via onItemClick(.....)
Is this a known issue? how to differentiate the events.
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;
}
EDIT
onCheckedChanged() is called
That's expected behavior:
onCheckedChanged(CompoundButton buttonView, boolean isChecked)
is called for every item, whenever they're checked/unchecked. Android has decided to track all items status for you and calls you for each item every time it was changed. With the isChecked
parameter you're able to differentiate what happened.
onItemClick()
is called whenever one of the items where clicked - that is not necessarily the checkbox within the item, but somewhere. Usually the item is selected afterwards - again, not always.
If you need to know which item was actually selected from the list view, use OnItemSelectedListener.onItemSelected()
. This is the one called to get the selection (whole item).
BTW: You dont need to prgram the behavior of a checkbox manually. The check/uncheck and drawing of the tick in the box is done by Android. You just need to get the checked status once you know which one was selected. So the onCheckedChanged
implementation is not necessary at all as far as I can see.