利用FrameLayout中图片的切换来实现换灯片

在上篇文章中利用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) {
    }
}
代码很简单通过在动画结束又重新启动动画来循环播放图片,希望对大家有用....

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值