不要更改资源图像

时间:2014-04-16 06:38:41

标签: android

我想通过两个静态图像制作一个动态图像,但是这个代码只是一个静态图像的闪光,现在我想分别在4s内闪现两个图像。

<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();
}

1 个答案:

答案 0 :(得分: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);

如果您希望它在其他图片上结束,请在1中添加或减去4 * 2