0

我试图让 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);

但我得到这个错误:

日志猫:

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.
4

2 回答 2

1
Only the original thread that created a view hierarchy can touch its views.

定时器任务在不同的线程上运行。ui 应该在 ui 线程上更新。

使用runOnUiThread.

runOnUiThread(new Runnable() {

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

        }
    });

您也可以使用Handler代替计时器。

编辑:

如果有帮助,请检查此setBackgroundResource 不设置图像

于 2013-12-14T13:14:00.823 回答
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);
于 2013-12-14T13:16:45.287 回答