[英]How to properly set custom long click listener?
I'm trying to set my own long click listener on Unlock button. 我试图在“解锁”按钮上设置自己的长按监听器。 Whenever I press the Unlock button it summarize duration and I can unlock permanently clicking.
每当我按下“解锁”按钮时,它就会总结持续时间,并且我可以永久地解锁。
Unlock.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(final View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Unlock.setText("Press to unlock");
isLongPress = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (isLongPress) {
Unlock();
}
}
}, longClickDuration); //amount of time of long click
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Unlock.setText("Unlock");
isLongPress = false;
}
return true;
}
});
}catch (Exception e) {
// TODO: handle exception
}
}
If you want to just handle long clicks consider using the following code: 如果您只想处理长点击,请考虑使用以下代码:
Unlock.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
your code
}
});
But if the Unlock();
但是如果
Unlock();
should be invoked after a certain (customizable) amount of time, you should measure this time in MotionEvent.ACTION_UP
handler. 应该在一定时间(可自定义)后调用,您应该在
MotionEvent.ACTION_UP
处理程序中测量该时间。 As @Attaullah Khan said, use SystemClock.elapsedRealtime()
system timer to correctly count number of milliseconds at two moments (when button was pressed and released) and if the time is greater than longClickDuration
then invoke Unlock
就像@Attaullah Khan所说的那样,请使用
SystemClock.elapsedRealtime()
系统计时器正确地计算两分钟(按下和释放按钮时)的毫秒数,如果时间大于longClickDuration
则调用Unlock
The handler.postDelayed
that you call in MotionEvent.ACTION_DOWN
handler just invokes a check of pressed state after longClickDuration
interval and if your button gets suddenly pressed at that moment, the verification passes that is not correct 该
handler.postDelayed
您在调用MotionEvent.ACTION_DOWN
处理程序只是调用按下状态的检查之后longClickDuration
间隔,如果你的按钮被在那一刻突然用力,验证通过,是不是正确的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.