在上篇文章中利用ViewFlipper来实现幻灯片但是最大的问题就是图片多了容易报内存溢出,现在我们使用FrameLayout中图片的切换始终FrameLayout中只有一张图片,这样很好的解决了内存溢出问题.
public class MainActivity extends Activity implements AnimatorListener {
private static final int ANIM_COUNT = 4;
private int[] urls = { R.drawable.c, R.drawable.g, R.drawable.h,
R.drawable.i, R.drawable.j, R.drawable.k, R.drawable.o };
private FrameLayout fLayout;
private ImageView mView;
private Random mRandom = new Random();
private int mIndex = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fLayout = (FrameLayout) findViewById(R.id.imagePager_FrameLayout);
}
//开始幻灯片
public void startSlide() {
mView = createNewView();
fLayout.addView(mView);
nextAnimation();
}
//加载图片
private ImageView createNewView() {
ImageView ret = new ImageView(this);
ret.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
ret.setScaleType(ScaleType.FIT_CENTER);
ret.setImageResource(urls[mIndex]);
mIndex = (mIndex + 1 < urls.length) ? mIndex + 1 : 0;
return ret;
}
//启动动画
private void nextAnimation() {
AnimatorSet anim = new AnimatorSet();
final int index = mRandom.nextInt(ANIM_COUNT);
switch (index) {
case 0:
anim.playTogether(
ObjectAnimator.ofFloat(mView, "scaleX", 1.5f, 1f),
ObjectAnimator.ofFloat(mView, "scaleY", 1.5f, 1f));
break;
case 1:
anim.playTogether(ObjectAnimator.ofFloat(mView, "scaleX", 1, 1.5f),
ObjectAnimator.ofFloat(mView, "scaleY", 1, 1.5f));
break;
case 2:
anim.playTogether(ObjectAnimator.ofFloat(mView, "alpha", 1f, 0f));
break;
case 3:
default:
anim.playTogether(ObjectAnimator.ofFloat(mView, "alpha", 0f, 1f));
break;
}
anim.setDuration(3000);
//动画监听
anim.addListener(this);
//开始动画
anim.start();
}
@Override
public void onAnimationCancel(Animator arg0) {
}
@Override
public void onAnimationEnd(Animator animator) {//动画结束触发的方法
//清除图片
fLayout.removeView(mView);
mView = createNewView();
//重新加载图片
fLayout.addView(mView);
//启动动画
nextAnimation();
}
@Override
public void onAnimationRepeat(Animator arg0) {
}
@Override
public void onAnimationStart(Animator arg0) {
}
}
代码很简单通过在动画结束又重新启动动画来循环播放图片,希望对大家有用....