Android中属性动画的使用

本文详细介绍了属性动画中的四种基本类型:透明、旋转、平移和缩放,并提供了具体的代码实现示例。此外,还讲解了如何使用AnimatorSet进行组合动画的制作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

属性动画分为:透明,旋转,平移,缩放

1.透明的实现方式:

效果图:

   mButton = (Button) findViewById(R.id.Button);
        // 创建动画作用对象:此处以Button为例

        ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "alpha", 1f, 0f, 1f);
        // 表示的是:
        // 动画作用对象是mButton
        // 动画作用的对象的属性是透明度alpha
        // 动画效果是:常规 - 全透明 - 常规
        animator.setDuration(5000);
        animator.start();

2.旋转的实现方式:

效果图:

mButton = (Button) findViewById(R.id.Button);
        // 创建动画作用对象:此处以Button为例

  ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "rotation", 0f, 360f);

        // 表示的是:
        // 动画作用对象是mButton
        // 动画作用的对象的属性是旋转alpha
        // 动画效果是:0 - 360
        animator.setDuration(5000);
        animator.start();

3.平移的实现方式:

效果图:

mButton = (Button) findViewById(R.id.Button);
        // 创建动画作用对象:此处以Button为例

  float curTranslationX = mButton.getTranslationX();
        // 获得当前按钮的位置
        ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "translationX", curTranslationX, 300,curTranslationX);


        // 表示的是:
        // 动画作用对象是mButton
        // 动画作用的对象的属性是X轴平移(在Y轴上平移同理,采用属性"translationY"
        // 动画效果是:从当前位置平移到 x=1500 再平移到初始位置
        animator.setDuration(5000);
        animator.start();

4.缩放的实现方式:

效果图:

mButton = (Button) findViewById(R.id.Button);
        // 创建动画作用对象:此处以Button为例

  ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "scaleX", 1f, 3f, 1f);
        // 表示的是:
        // 动画作用对象是mButton
        // 动画作用的对象的属性是X轴缩放
        // 动画效果是:放大到3倍,再缩小到初始大小
        animator.setDuration(5000);
        animator.start();

组合动画的使用:AnimatorSet

组合动画的基本操作:

  1. AnimatorSet.play(Animator anim) :播放当前动画
  2. AnimatorSet.after(long delay) :将现有动画延迟x毫秒后执行
  3. AnimatorSet.with(Animator anim) :将现有动画和传入的动画同时执行
  4. AnimatorSet.after(Animator anim) :将现有动画插入到传入的动画之后执行
  5. AnimatorSet.before(Animator anim) : 将现有动画插入到传入的动画之前执行

主要的代码实现步骤:

// 步骤1:设置需要组合的动画效果
ObjectAnimator translation = ObjectAnimator.ofFloat(mButton, "translationX", curTranslationX, 300,curTranslationX);  
// 平移动画
ObjectAnimator rotate = ObjectAnimator.ofFloat(mButton, "rotation", 0f, 360f);  
// 旋转动画
ObjectAnimator alpha = ObjectAnimator.ofFloat(mButton, "alpha", 1f, 0f, 1f);  
// 透明度动画

// 步骤2:创建组合动画的对象
AnimatorSet animSet = new AnimatorSet();  

// 步骤3:根据需求组合动画
animSet.play(translation).with(rotate).before(alpha);  
animSet.setDuration(5000);  

// 步骤4:启动动画
animSet.start();  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拉莫帅

你的鼓励将是我的创作动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值