[英]How to keep adding while button is pressed?
I'm building a simple counter, it has buttons to add or subtract from a total value, I want it to keep adding if I hold the button, incrementing +5 every second, but i'm having problems to make it work. 我正在构建一个简单的计数器,它具有可在总值中增加或减少的按钮,如果我按住该按钮,则希望它继续增加,每秒增加+5,但是我在使其工作方面遇到问题。 I'm using onClickListener, but i can't find a way to make it work "together" with on touch listener. 我正在使用onClickListener,但是我找不到找到使其与触摸式监听器“一起”工作的方法。
pl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
lf++;
lt.setText(Integer.toString(lf));
}
}
You will have to use handler to schedule a runnable that increments +5 every 1 second (+1 per 200 milliseconds to keep it smooth) 您将必须使用处理程序来安排一个可运行对象,该可运行对象每1秒递增+5(每200毫秒+1以使其保持平稳)
Handler handler = new Handler();
Runnable incrementTask = new Runnable(){
@Override
public void run(){
lf++;
handler.postDelayed(incrementTask, 200); //Execute after 200 milliseconds
}
};
Then you implement onTouchListener and post this runnable when ACTION_DOWN is dispatched and cancel it when ACTION_UP is dispatched. 然后,您实现onTouchListener并在调度ACTION_DOWN时发布此可运行对象,并在调度ACTION_UP时将其取消。
boolean buttonPressed = false;
pl.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
//This check is imporant since ACTION_DOWN might be called
// multiple times when finger is moving
if(!buttonPressed){
buttonPressed = true;
handler.post(incrementTask);
}
} else if(event.getAction() == MotionEvent.ACTION_UP){
if(buttonPressed)
{
buttonPressed = false;
handler.cancel(incrementTask);
}
}
return false;
}
});
Please note that this logic won't work well with your current click listener. 请注意,此逻辑不适用于您当前的点击监听器。 For better user experience, I would recommend that you start this timer/runnable only when your button is long pressed . 为了获得更好的用户体验,我建议您仅在长按按钮时启动此计时器/可运行计时器。 I had a similar situation in a project so I wrote a utility class to help me detect when a button is being held and released after a long click. 我在项目中也遇到过类似情况,因此我编写了一个实用程序类来帮助我检测长时间单击后何时按住和释放按钮。 Normal clicks work fine as well. 正常点击也可以正常工作。 You can find my ClickAndHoldManager class on Github . 您可以在Github上找到我的ClickAndHoldManager类。
To use it, you simply pass your view in the constructor and set a listener: 要使用它,只需在构造函数中传递视图并设置一个侦听器:
ClickAndHoldManager manager = new ClickAndHoldManager(myButton);
manager.setClickCallback(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Regular Click
}
});
manager.setHoldCallback(new ClickAndHoldManager.HoldListener() {
@Override
public void holdStarted() {
// do handler.post() here
}
@Override
public void holdEnded() {
//do handler.cancel() here
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.