[英]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: 我有一个活动,我有一个按钮,当单击此按钮时,我想为TextView设置一些值,所以我使用了onClickListening,它可以正常工作:
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: 但是问题是我想在不断按下按钮的同时继续增加此textView的值,所以我尝试使用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. 问题是,当我快速单击按钮时,它会使TextView的值增加太多,并且我希望在按下按钮一段时间后才能激活onTouchListener。
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. 您可以根据需要设置
X
,即将其设置为5
会使触摸事件的运行速度降低5
倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.