我们如何通过触摸事件模拟长按,或者如何计算屏幕在ACTION_DOWN状态下被触摸的时间?
我们如何通过触摸事件模拟长按,或者如何计算屏幕在ACTION_DOWN状态下被触摸的时间?
我终于成功实现了触摸屏长按功能,感谢大家。
textView.setOnTouchListener(new View.OnTouchListener() {
private static final int MIN_CLICK_DURATION = 1000;
private long startClickTime;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
longClickActive = false;
break;
case MotionEvent.ACTION_DOWN:
if (longClickActive == false) {
longClickActive = true;
startClickTime = Calendar.getInstance().getTimeInMillis();
}
break;
case MotionEvent.ACTION_MOVE:
if (longClickActive == true) {
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
if (clickDuration >= MIN_CLICK_DURATION) {
Toast.makeText(MainActivity.this, "LONG PRESSED!",Toast.LENGTH_SHORT).show();
longClickActive = false;
}
}
break;
}
return true;
}
});
其中private boolean longClickActive = false;
是一个类变量。
试试这个。你不需要去寻找对此的黑客攻击。
final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
public void onLongPress(MotionEvent e) {
Log.e("", "Longpress detected");
}
});
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
};