用户触摸屏幕时调用的事件?

时间:2015-01-25 12:19:33

标签: android ontouchlistener ontouchevent motionevent

欢迎所有

我正在开发一款游戏。我希望当用户触摸屏幕时,必须每隔100ms从屏幕底部到触摸的x,y坐标不断地发射激光,直到用户停止触摸屏幕。我有激光工作,但现在我需要每100毫秒不断发射。

我正在开发onTouch事件,问题是我不知道如何实现我的需求。如果用户正在触摸屏幕,我想每100毫秒启动一次激光。

如果我将激光动画放在onTouch MotionEvent.ACTION_MOVE事件中,那么只有在手指移动时才会抛出激光。但我希望激光每100毫秒抛出一次而不会移动手指。

此外,MotionEvent.ACTION_DOWN无法正常工作,因为当用户触摸屏幕但只有一次时,它只被调用一次

我的需求如何实现?

2 个答案:

答案 0 :(得分:2)

没有一种简单的方法可以每100毫秒获得一次活动

但你可以这样做:

        class TouchStarted {
        AtomicBoolean actionDownFlag = new AtomicBoolean(true);

        Thread loggingThread = new Thread(new Runnable(){

            public void run(){
                while(actionDownFlag.get()){
                    Log.d("event", "Touching Down");
                    try {
                       Thread.sleep(100, 0);
                    } catch (InterruptedException e) {
                    }
                    //maybe sleep some times to not polute your logcat
                }
                Log.d("event", "Not Touching");
            }
        });

        public void stop() {
            actionDownFlag.set(false);
        }

        public void start() {
            actionDownFlag.set(true);
            loggingThread.start();
        }

    }

    TouchStarted last = null;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if(event.getAction()==MotionEvent.ACTION_DOWN){
            if(last != null) last.stop();
            last = new TouchStarted();
            last.start();
        }
        if(event.getAction()==MotionEvent.ACTION_UP){
            last.stop();
        }
    }

答案 1 :(得分:1)

您可以在ACTION_DOWN中尝试这样的事情

Thread thread = new Thread(new Runnable){
    @Override
    public void run(){
        while(yourFlag) //figure out something to set up a loop 
          try{ 

            yourfirelasermethod();  
            Thread.sleep(100);     // this waits 100ms until firing             
                                   // again
         }catch(Exception e){

         }
    }
}).start();
相关问题