2011-08-25 87 views
2

就在一個快速的等待命令後,我的應用程序停止了,比如說10毫秒,這樣看起來就像是動畫素材(在我的情況下是一個球)。尋找一個快速的'n簡單的等待命令

public class PiranhaDrop extends Activity 
    { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    FrameLayout main = (FrameLayout) findViewById(R.id.main_view); 
    main.addView(new Drawing(this,0,0,0)); 
    int MyLoop=0; 
    while(MyLoop<100) 
    { 
     main.addView(new Drawing(this,MyLoop,10,10)); 
     synchronized(this){wait(10);} 
     //try{Thread.sleep(WaitTime);} catch (InterruptedException e){} 
     MyLoop=MyLoop+1; 
     main.setOnTouchListener(new View.OnTouchListener() 
     { 
      public boolean onTouch(View v, MotionEvent e) 
      { 
       float x = e.getX(); 
       float y = e.getY(); 
       FrameLayout flView = (FrameLayout) v; 
       flView.addView(new Drawing(getParent(),x,y,25)); 
       return false; 
      } 
     }); 
    } 
} 

}

正如你所看到的,在循環開始後,剛剛我已經試過幾件事情(在WAITTIME指長,我擺脫了,它不工作) - 既不是其中有工作。

謝謝。

回答

1

的正確方法等是這樣的:

try 
{ 
    Thread.sleep(10); 
} 
catch (Exception e){} 

但是,請注意,這將在UI線程上運行。 對於10ms來說,沒有真正的問題,並且這是等待的首選方式......但是,如果時間較長,它會導致用戶發出醜陋的對話,說您的應用程序沒有響應。

+0

正如你所說 - 在UI線程中調用sleep()是一個糟糕的做法。所以不要把它作爲解決方案。 –

+0

我不同意。對於10ms這是一個好方法...雖然我不知道10ms睡眠會達到什麼 – IncrediApp

+0

認爲我已經使用了上面的IncrediApp的代碼。 Eclipse中的模擬器不太喜歡它,但我會看看我能否正常工作。 – djmcbell