Hoo Hoo - 14 days ago 4
Android Question

Button display checkbox counter

I have a listView with checkBox. When checkBox is checked/unchecked, it will count and display the number in

button
delete
setText. If the counter is equal to 0, then it will only display
DELETE
, otherwise it will display
DELETE (with the counter)
. But the problem is the delete still setText
DELETE (with the counter)
although the counter is 0.

holder.ckbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
int getPosition = (Integer) v.getTag(); // Here we get the position that we have set for the checkbox using setTag.
search.get(getPosition).setSelected(((CheckBox)v).isChecked()); // Set the value of checkbox to maintain its state.
checkBoxCounter ++;
delete.setText("DELETE"+""+"("+ checkBoxCounter +")");
} else
{
if(checkBoxCounter==0)
{
delete.setText("DELETE");
}
else {
int getPosition = (Integer) v.getTag(); // Here we get the position that we have set for the checkbox using setTag.
search.get(getPosition).setSelected(((CheckBox) v).isChecked()); // Set the value of checkbox to maintain its state.
checkBoxCounter--;
delete.setText("DELETE" + "" + "(" + checkBoxCounter + ")");
}
}
}
});

Answer

Right now you're never checking for 0. Change the bottom else block to this:

else {
   int getPosition = (Integer) v.getTag();  // Here we get the position that we have set for the checkbox using setTag.
   search.get(getPosition).setSelected(((CheckBox) v).isChecked()); // Set the value of checkbox to maintain its state.
   checkBoxCounter--;
   if (checkBoxCounter == 0) {
      delete.setText("DELETE");
   else {
      delete.setText("DELETE" + "" + "(" + checkBoxCounter + ")");
   }
}

and remove the earlier check

Comments