【问题标题】:How to make an ImageSwitcher switch the image every 5 secs?如何让图像切换器每 5 秒切换一次图像?
【发布时间】:2013-12-14 13:10:58
【问题描述】:

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

【问题讨论】:

    标签: android timer imageview imageswitcher


    【解决方案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);
    

    【讨论】:

      【解决方案2】:
      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 doesn't set the image

      【讨论】:

        猜你喜欢
        • 2015-12-25
        • 1970-01-01
        • 2013-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-05
        相关资源
        最近更新 更多