Counting clicks using integer++ OnTouchListener
-
21-12-2019 - |
Question
I have a method to count clicks and then do something after some number of clicks. It works fine but there is a problem with OnTouchListener. The problem is as long as user is pressing button, integer is increasing and count number is incorrect. Instead of 1 click I get like 10-15 depends how much time user is pressing button. How can I make it to add +1 per click? My Method:
private void clickCounter() {
String valueFromFile = read("countFile");
int intClickCounter = Integer.valueOf(valueFromFile.toString());
intClickCounter++;
valueFromFile = Integer.toString(intClickCounter);
write("" + valueFromFile, "countFile");
Toast.makeText(MainActivity.this, valueFromFile, Toast.LENGTH_SHORT)
.show();
if (intClickCounter == 10) {
And then onTouchListener:
@Override
public boolean onTouch(View v, MotionEvent event) {
int id = v.getId();
clickCounter();
switch(id){
case R.id.button1:
etc
Solution
Just apply this following condition
clickButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction()==MotionEvent.ACTION_UP){
clickCounter();
}
return false;
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow