2014-04-16 35 views
0

我想通过两个静态图像做一个动态图像,但是这个代码只是一个静态图像的闪光,现在我想分别在4秒内闪烁两个图像。不要改变resoucre图像

<ImageSwitcher 
    android:id="@+id/imageswitcherID" 
    <!-- insert another value to the view like layout width and height or margin --> 
    android:inAnimation="@anim/fade_in" 
    android:outAnimation="@anim/fade_out" 
    > 

    <ImageView 
     android:id="@+id/imageview1" 
     <!-- another value here --> 
     android:background="@drawable/your_drawable01" 
     /> 

    <ImageView 
     android:id="@+id/imageview2" 
     <!-- another value here --> 
     android:background="@drawable/your_drawable02" 
     /> 

</ImageSwitcher> 

,现在继续您的活动,创建线程循环,持续4秒

int seconds = 0; 
ImageSwitcher imgswitch; 
... 
@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.your_layout); 

    imgswitch = (ImageSwitcher)findViewById(R.id.imageswitcherID); 

    SwitchingImages(); 
} 
... 
private void SwitchingImages(){ 
    Thread SwImg = new thread(){ 
     @Override 
     public void run(){ 
      try{ 
       while(seconds <= 4){ 
        sleep(1000); //sleep for 1 seconds 
        runOnUiThread(new Runnable(){ 
         @Override 
         public void run(){ 
          imgswitch.showNext(); //will switch images every 1 seconds 
          if(seconds >= 5){ 
           return; //stop the thread when 4 seconds elapsed 
          } 
          seconds += 1; 
         } 
        }); 
       } 
      }catch(InterruptedException e){ 
       e.printStackTrace(); 
      } 
     } 
    }; 
    SwImg.start(); 
} 
+0

你只是想让图像在4秒后或者每4秒重复一次? –

+0

我只是想让它切换一次4秒。但代码只显示一个图像。我想分别在4秒后显示2张图像。 – giangdaughtry

回答

1

这是很容易用RunnableView.postDelayed()方法来做。删除SwitchingImages()方法,并将其放在imgswitch = ...后面。

imgswitch.postDelayed(
    // Here we create an anonymous Runnable 
    // to switch the image and repost 
    // itself every 0.5 * 1000 milliseconds 
    // until count = 8 
    new Runnable() 
    { 
     int count = 0; 

     @Override 
     public void run() 
     { 
      if (count < 4 * 2) 
      { 
       imgswitch.showNext(); 
       count++; 
       imgswitch.postDelayed(this, 500); 
      } 
     } 
    } 
    , 500); 

如果你希望它结束​​的其他图像上,添加或4 * 2减去1

+0

当然,如果你确定'ImageSwitcher'的图像和动画是正确的,那么这只会起作用。 –

+0

谢谢,但它不工作,我想要的,你已经改变了2个图像出现在4s,但我想每0.5s图像a将取代图像b,并相反。 4秒后会结束。 – giangdaughtry

+0

好吧,让我看看我是否明白。您希望图像每0.5秒切换一次,然后在4秒后停止切换。这是正确的吗? –