Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onCheckedChanged fired multiple times, Listview with checkbox

I have a ListView with checkbox:

  1. Oncheckedchanged(..) is called when user check/uncheck item on listview
  2. OncheckedChanged(..) 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

  1. Once when no item are selected and user clicks the checkbox
  2. If the list consists of 3 items and when user click on any other items, onItemclick() is invoked and onCheckedChanged() is fired 3 times ( =no: of items in the listview)
like image 833
user755 Avatar asked Oct 04 '13 18:10

user755


1 Answers

Replace the onCheckChangeListener to onClickListener.

The checkChanged will be called twice as it will be called when you call setChecked() method and when you click on the checkbox.

like image 165
kapil thadani Avatar answered Sep 30 '22 23:09

kapil thadani