SurfaceView上的长触摸(android)

Nio*_*199 7 multithreading android touch long-press

我在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;
Run Code Online (Sandbox Code Playgroud)

这是有效的,但只有当用户停止触摸手机时,我才能检测到印刷机是否长按.所以这不是我想要的.我更喜欢当用户第一次触摸屏幕时启动计时器,然后一旦经过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;
                    }
                }
            }
    }
Run Code Online (Sandbox Code Playgroud)

有谁有任何想法?另一个解决方案也将受到欢迎.

谢谢.

Mat*_*all 3

当您还想进行一些手动事件处理时,一个不错的选择是 GestureDetector 类:http://developer.android.com/reference/android/view/GestureDetector.html

我如何使用它是在构造函数中创建一个 GestureDetector 实例,实现我感兴趣的方法,然后在 onTouchEvent() 方法的开头执行如下操作:

    if (gestureDetector.onTouchEvent(event)) {
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

这意味着在大多数情况下,当检测到手势时,会中止其余的触摸处理。然而,长按有点不同,因为长按方法不返回值。在这种情况下,我只是在长按触发时设置了一个布尔值,如果需要的话,我稍后会在触摸事件处理方法中进行检查。