2013-12-14 77 views
0

我試着去得到一個ImageSwitcher改變的圖像,每5秒..如何使ImageSwitcher每5秒切換一次圖像?

我試圖用一個Timer

Timer t = new Timer(); 
      //Set the schedule function and rate 
      t.scheduleAtFixedRate(new TimerTask() { 

       public void run() { 
        //Called each time when 1000 milliseconds (1 second) (the period parameter) 
        currentIndex++; 
       // If index reaches maximum reset it 
       if(currentIndex==messageCount) 
        currentIndex=0; 
       imageSwitcher.setImageResource(imageIds[currentIndex]); 
       } 

      },0,5000); 

但我得到這個錯誤:

的logcat:

12-14 15:07:29.963: E/AndroidRuntime(25592): FATAL EXCEPTION: Timer-0 
12-14 15:07:29.963: E/AndroidRuntime(25592): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 

回答

1
Timer t = new Timer(); 
     //Set the schedule function and rate 
     t.scheduleAtFixedRate(new TimerTask() { 

      public void run() { 
       //Called each time when 1000 milliseconds (1 second) (the period parameter) 
       currentIndex++; 
      // If index reaches maximum reset it 
      if(currentIndex==messageCount) 
       currentIndex=0; 
      runOnUiThread(new Runnable() { 

       public void run() { 
        imageSwitcher.setImageResource(imageIds[currentIndex]); 

       } 
      }); 
      } 

     },0,5000); 
1
Only the original thread that created a view hierarchy can touch its views. 

定時器任務運行在di不同的線程。 Ui應該在ui線程上更新。使用runOnUiThread。您可以使用Handler而不是定時器。

編輯:

檢查這個setBackgroundResource doesn't set the image如果它可以幫助