Givemepass's Android 惡補筆記

如何讓ImageView產生淡入淡出的效果

| Comments

如果想要讓ImageView在一系列的圖片進行切換,

又要有淡入淡出的效果怎麼做呢?


一開始先宣告ImageView, 並且指定一張圖片

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/raccoon"
        android:id="@+id/img" />

</RelativeLayout>

接著設定fade out 讓目前的圖片淡出, 當動畫結束以後, 則呼叫圖片淡入,
這時候只要指定下一張圖片, 就可以無限輪播了。

private void fadeOutAndHideImage(final ImageView img){
    Animation fadeOut = new AlphaAnimation(1, 0);
    fadeOut.setInterpolator(new AccelerateInterpolator());
    fadeOut.setDuration(2000);

    fadeOut.setAnimationListener(new AnimationListener()
    {
        public void onAnimationEnd(Animation animation) 
        {
              nowPicPos %= 2;
              img.setImageResource(imgRes[nowPicPos]);
              nowPicPos++;
              fadeInAndShowImage(img);
        }
        public void onAnimationRepeat(Animation animation) {}
        public void onAnimationStart(Animation animation) {}
    });

    img.startAnimation(fadeOut);
}
private void fadeInAndShowImage(final ImageView img){
    Animation fadeIn = new AlphaAnimation(0, 1);
    fadeIn.setInterpolator(new AccelerateInterpolator());
    fadeIn.setDuration(2000);

    fadeIn.setAnimationListener(new AnimationListener()
    {
        public void onAnimationEnd(Animation animation) 
        {
              fadeOutAndHideImage(img);
        }
        public void onAnimationRepeat(Animation animation) {}
        public void onAnimationStart(Animation animation) {}
    });

    img.startAnimation(fadeIn);
}

主程式

private ImageView mImageView;

private int nowPicPos = 0;

private int[] imgRes = {R.drawable.panda, R.drawable.raccoon};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mImageView = (ImageView) findViewById(R.id.img);
    fadeOutAndHideImage(mImageView);
}

目前以兩張圖片為例子, 如果要播放一系列 , 只需要多放幾張圖就好。

程式碼
http://uploadingit.com/file/kcgsdyamvweki5zg/SwitchImageViewDemo.zip

https://dl.dropboxusercontent.com/u/24682760/Android/SwitchImageViewDemo/SwitchImageViewDemo.zip

Comments

comments powered by Disqus