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();
should be invoked after a certain (customizable) amount of time, you should measure this time in MotionEvent.ACTION_UP
handler. 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
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
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.