2014-02-22 75 views
1

我這是爲了我的滾動圖片視圖,使其落在每0.1秒5個像素的功能,但是當我運行這個功能我得到Sorry Application has stopped respondingJava Android - ImageView滾動導致崩潰?

你可以看看下面我的代碼:

void startGameLoop(){ 
    boolean alive=true; 
    while(alive){ 

     int x = theSprite.getScrollX(); 
     int y = theSprite.getScrollY(); 
     y-=5; 
     theSprite.scrollTo(x, y); 
     try { 
      Thread.sleep(100); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 

對此的任何幫助將不勝感激。

+0

請添加logcat!到目前爲止,我看起來像是一個永恆的循環。我的意思是什麼時候會'活着==假' – donfuxx

回答

0

如果你把這個代碼Thread.sleep(100);在主線程上會發生。 代之以延遲使用處理程序。該處理程序可以更改諸如ImageView之類的內容,因爲它在主Ui線程上運行。 類似這樣的..

private final Runnable timerRunnable = new Runnable() { 
    @Override 
    public void run() { 
     int x = theSprite.getScrollX(); 
     int y = theSprite.getScrollY(); 
     y-=5; 
     theSprite.scrollTo(x, y); 
     if (!closing) 
      startTimer(); 
    } 
}; 

handler = new Handler(); 
startTimer(); 

/** 
* Start periodically callbacks. 
*/ 
private void startTimer() { 
    runOnUiThreadDelay(timerRunnable, 400L); 
} 

public void runOnUiThreadDelay(final Runnable runnable, long delayMillis) { 
    handler.postDelayed(runnable, delayMillis); 
} 
+0

肯定有辦法做到這一點與睡眠?你這樣做的方法看起來非常複雜,再加上我似乎無法使其工作,我得到了一堆錯誤。 – user3341661

+0

Nop,如果你睡在主線程上,你的應用就會睡覺。延遲處理程序未在主UI線程上睡眠。這是一個線程,它允許在UI中改變事物。只要把'handler = new Handler();和startTimer();'在你的oncreate(),它會開始每400mili – Erik

+0

感謝您的幫助,這是現在工作:) – user3341661