又要有淡入淡出的效果怎麼做呢?
一開始先宣告ImageView, 並且指定一張圖片
<?xml version="1.0" encoding="utf-8"?>
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<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);
}
目前以兩張圖片為例子, 如果要播放一系列 , 只需要多放幾張圖就好。Eclipse 程式碼
Android Studio程式碼