我在Android上制作游戏,当用户尝试在屏幕上长按时我需要执行某些操作。不幸的是,我还没有找到任何直接使用自定义SurfaceView的方法,随时告诉我,如果这种方法存在:)长时间触摸surfaceView(android)
所以我决定试着从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;
这工作,但只有当用户停止触摸手机,我可以检测,如果记者是一个长按或不。所以这不完全是我想要的。我宁愿如果一个计时器会在用户第一次触摸屏幕时开始,那么一旦800ms过去,LongTouch()方法被调用。换句话说,我不想检查ACTION_UP自ACTION_DOWN以来已经过了多长时间。我相信我应该为这个计时器使用一个线程,但是我不能让它工作。
@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;
}
}
}
}
有没有人有任何想法:如果使用下面的代码,是当我触摸屏幕上显示的调试信息?另一个解决方案也是受欢迎的。
谢谢。