描述
最近听见有人争论长按的时长有多长,有人说是400毫秒,有人说是500毫秒。其实两种说法都对,AndroidSDK版本不同,时长也不一样。
验证
长按点击事件:
new View(this).setOnLongClickListener(v -> false);
点击事件执行在MotionEvent.ACTION_DOWN时,也就是手指按下时。长按点击事件其实就是一种延时操作。
case MotionEvent.ACTION_DOWN:
if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
}
mHasPerformedLongPress = false;
// 不是单击事件
if (!clickable) {
// 检查是否是长按事件,若是则执行
checkForLongClick(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
break;
}
其中checkForLongClick:
private void checkForLongClick(long delay, float x, float y, int classification) {
if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.setAnchor(x, y);
mPendingCheckForLongPress.rememberWindowAttachCount();
mPendingCheckForLongPress.rememberPressedState();
mPendingCheckForLongPress.setClassification(classification);
// post一个延时事件
postDelayed(mPendingCheckForLongPress, delay);
}
}
...
// post延时事件Runnable
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().postDelayed(action, delayMillis);
return true;
}
其中delay就是长按的延时时间,也就是长按的判断时间,也就是ViewConfiguration.getLongPressTimeout()的时长。
/**
* @return the duration in milliseconds before a press turns into
* a long press
*/
public static int getLongPressTimeout() {
return AppGlobals.getIntCoreSetting(Settings.Secure.LONG_PRESS_TIMEOUT,
DEFAULT_LONG_PRESS_TIMEOUT);
}
所以长按时长的争议点在于DEFAULT_LONG_PRESS_TIMEOUT的数值。
在AndroidSDK-29中,该时长为500毫秒。
/**
* Defines the default duration in milliseconds before a press turns into
* a long press
*/
private static final int DEFAULT_LONG_PRESS_TIMEOUT = 500;
在AndroidSDK-28中也是500毫秒。
但是在AndroidSDK-30中,该时长变成了400毫秒。
/**
* Defines the default duration in milliseconds before a press turns into
* a long press
* @hide
*/
public static final int DEFAULT_LONG_PRESS_TIMEOUT = 400;
在AndroidSDK-31中为400毫秒。
总结
长按时长在AndroidSDK-29(包含29)及以下版本为500毫秒,大于29版本时长为400毫秒。