我正在 Android 上制作游戏,当用户尝试长按屏幕时,我需要执行某些操作。不幸的是,我还没有找到任何直接与自定义 SurfaceView 一起使用的方法,请随时告诉我是否存在这样的方法 :)
所以我决定尝试从 onTouch 事件监听器实现长触摸检测。
这是我的代码:
@Override
public boolean onTouch(View v, MotionEvent event)
{
long touchDuration = 0;
if ( event.getAction() == MotionEvent.ACTION_DOWN )
{
//Start timer
touchTime = System.currentTimeMillis();
}else if ( event.getAction() == MotionEvent.ACTION_UP )
{
//stop timer
touchDuration = System.currentTimeMillis() - touchTime;
if ( touchDuration < 800 )
{
onShortTouch(event,touchDuration);
}else
{
onLongTouch(event,touchDuration);
}
}
}
return true;
这可行,但我可以检测到按下是否是长按,或者不仅是当用户停止触摸手机时。所以这不是我想要的。我更喜欢在用户第一次触摸屏幕时启动计时器,然后一旦经过 800 毫秒,就会调用 LongTouch() 方法。换句话说,我不想检查自 ACTION_DOWN 以来 ACTION_UP 已经过去了多长时间。我相信我应该为所述计时器使用线程,但我无法使其工作。使用以下代码时,只要触摸屏幕就会显示调试消息:
@Override
public boolean onTouch(View v, MotionEvent event)
{
long touchDuration = 0;
TouchThread touchThread = new TouchThread();
if ( event.getAction() == MotionEvent.ACTION_DOWN )
{
//Start timer
touchTime = System.currentTimeMillis();
touchThread.setEvent(event);
touchThread.run();
}
return true;
}
private class TouchThread extends Thread
{
public MotionEvent event = null;
public void setEvent(MotionEvent e)
{
event = e;
}
@Override
public void run()
{
long startTime = System.currentTimeMillis();
long time = 0;
while(event.getAction() == MotionEvent.ACTION_DOWN)
{
time = System.currentTimeMillis() - startTime;
if( time > 800 )
{
System.out.println("LOOONG CLICK!!");
return;
}
}
}
}
有人知道吗?其他解决方案也将受到欢迎。
谢谢。