【问题标题】:onTouchEvent hold down, continuous executiononTouchEvent 按住不放,持续执行
【发布时间】:2015-02-23 03:38:49
【问题描述】:

在我的 onTouchEvent() 方法中,我想执行一个不断重复的动作,直到我将手指从屏幕上移开。这是我的代码:

public void onTouchEvent(MotionEvent event) {
    synchronized (this) {
        Matrix matrix = new Matrix();

        float x = event.getX();
        if (x >= screenWidth / 2) {
            rotate += 10;
        } else {
            rotate -= 10;
        }
        matrix.postRotate(rotate, square.getWidth() / 2, square.getHeight() / 2);
        position.set(matrix);
        position.postTranslate(xPos, yPos);
    }
    return true;
}

但问题是,如果我按住手指不移动,动作只会执行一次。我尝试了各种解决方案,包括

boolean actionUpFlag = false;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
    actionUpFlag = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
    actionUpFlag = false;
}

while (actionUpFlag) {
    //the block of code above        
}

只有当事件是 MotionEvent.ACTION_MOVE 时才执行动作,并在 onTouchEvent() 结束时返回 false,所有这些都不成功。谁能告诉我错误是什么?

MotionEvent.ACTION_MOVE 尝试的代码块:

if (event.getAction() == MotionEvent.ACTION_MOVE) {
    //block of code above
}

【问题讨论】:

    标签: android touch


    【解决方案1】:

    您是否考虑过使用Thread 来完成此操作?

    这里已经很晚了(我已经工作了 13 个小时),但这应该会给你一个要点:

    WorkerThread workerThread;
    
    public void onTouchEvent(MotionEvent event){
    
    
        int action = event.getAction();
    
        switch(action){
            case MotionEvent.ACTION_DOWN:
                if (workerThread == null){
                    workerThread = new WorkerThread();
                    workerThread.start();
                }
                break;
            case MotionEvent.ACTION_UP:
                if (workerThread != null){
                    workerThread.stop();
                    workerThread = null;
                }
                break;
            }
        return false;
    }
    

    您的 Thread 实现可能是一个内部类,例如:

    class WorkerThread extends Thread{
    
        private volatile boolean stopped = false;
    
        @Override
        public void run(){
            super.run();
            while(!stopped){
                //do your work here
            }   
        }
    
        public void stop(){
            stopped = true;
        }
    }
    

    您可能只想忽略MotionEvent.ACTION_MOVE,除非您想执行不同的操作。

    如果您使用WorkerThread 更新您的用户界面,请确保以线程安全的方式进行。

    Here is a link to the Android API Guide on Processes and Threads

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多