简体   繁体   中英

Android - OnTouchListener() is triggered too early

I have an activitiy where I have a button and when a click on this button I want to set a TextView with some value, so I used onClickListening and it is working:

   ButtonPlus.setOnClickListener(new Button.OnClickListener() {

    @Override
    public void onClick(View v) {
     ponts = ponts + 1;
     resultadoTextView.setText(Integer.toString(ponts));

     }
 }); 

But the problem is that I want to keep increasing this textView's value while the button keep being pressed so I tried to use the OnTouchLister:

ButtonPlus.setOnTouchListener(new View.OnTouchListener() {

  @Override
  public boolean onTouch(View v, MotionEvent event) {

       ponts = ponts + 1;
       resultTextView.setText(Integer.toString(ponts)); 

 }
});

the problem is that when I give a fast click in the button it increments the TextView's value too much and I want the onTouchListener to be activated just after some time that the button was pressed.

any help please?

Try this code.

ButtonPlus.setOnTouchListener(new View.OnTouchListener() {

   @Override
   public boolean onTouch(View v, MotionEvent event) {

        ponts = ponts + 1;
        resultTextView.setText(Integer.toString(ponts)); 
        ButtonPlus.setClickable(false);

        //wait 1 second
        ButtonPlus.postDelayed(new Runnable() {

            @Override
            public void run() {
                ButtonPlus.setClickable(true);                        
            }
        }, 1000);

        return false;

  }
});

Use some additional counter.

int additionalCounter = 0;

ButtonPlus.setOnTouchListener(new View.OnTouchListener() {

  @Override
  public boolean onTouch(View v, MotionEvent event) {

    ++additionalCounter;
    if (additionalCounter % X == 0) {
      ponts = ponts + 1;
      resultTextView.setText(Integer.toString(ponts));
    }

  }  
});

You can set X as you want, ie setting it to 5 would make touch event working 5 times slower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM