Kewin Björk Nielsen Kewin Björk Nielsen - 4 months ago 23
Android Question

How to reset a click counter?

I have an implementation where, on every click of a button, a counter is increased and the counter is shown in a

TextView
. There's a reset button that is supposed to set the counter back to 0, so that the count can start again from zero when the
btn_take_photo
button is pressed. Here's my code:

private int counter = 0;
btn_take_photo.setOnClickListener(new FloatingActionButton.OnClickListener() {
@Override
public void onClick(View view) {
counter++;
count.setText(String.valueOf(counter));
}
});


This is the method called by the button (
btn_approve
) that is supposed to reset the counter:

public void btn_aprove (View view)
{ count.setText("0");

}


When I click
btn_approve
, the
TextView
shows 0. But, when I press
btn_take_photo
again, the counter starts from the last set value instead of 1. For instance, if I reset the counter when
count
is 6, the
TextView
reads 0. Then if I press
btn_take_photo
, the counter shows 6 again.

Answer

You also have to set the variable counter back to 0.

So your "Reset"-function should look like this:

public void btn_aprove (View view)
    {        
        count.setText("0");
        counter = 0;
    }
Comments