2015-02-23 44 views
0

在我的onTouchEvent()方法中,我想要執行一個操作,繼續自我重複,直到我將手指從屏幕上擡起。這裏是我的代碼: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 
} 

回答

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