返回
Android从零撸美团(二) - 仿美团下拉刷新自定义动画
Android
2024-02-18 08:39:38
三种状态,三种动画
我们先看看美团的这款下拉加载动画:
- 第一种状态: 刚开始下拉的时候,小脑袋从小变大。
- 第二种状态: 下拉到一定程度但还没松手,小人翻了个跟头。
- 第三种状态: 松手后变回初始状态。
这三种状态,对应三种不同的动画。那么,我们该怎么实现呢?
卖萌小人的第一步
我们先来实现最简单的第一种状态:下拉后小脑袋变大。
要实现这个动画,我们需要用到一个 ScaleAnimation
类。这个类可以让我们对小人进行缩放动画。
// 创建 ScaleAnimation 对象
ScaleAnimation scaleAnimation = new ScaleAnimation(0.5f, 1.0f, 0.5f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// 设置动画的持续时间
scaleAnimation.setDuration(300);
// 设置动画的重复次数
scaleAnimation.setRepeatCount(Animation.INFINITE);
// 设置动画的重复模式
scaleAnimation.setRepeatMode(Animation.REVERSE);
// 为小人添加动画
小人.startAnimation(scaleAnimation);
这段代码的作用很简单:
- 创建一个
ScaleAnimation
对象,并设置它的参数。 - 设置动画的持续时间、重复次数和重复模式。
- 为小人添加动画。
第二种状态的跳跃时刻
第二种状态是下拉到一定程度但还没松手,小人翻了个跟头。
要实现这个动画,我们需要用到一个 RotateAnimation
类。这个类可以让我们对小人进行旋转动画。
// 创建 RotateAnimation 对象
RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// 设置动画的持续时间
rotateAnimation.setDuration(300);
// 设置动画的重复次数
rotateAnimation.setRepeatCount(Animation.INFINITE);
// 设置动画的重复模式
rotateAnimation.setRepeatMode(Animation.REVERSE);
// 为小人添加动画
小人.startAnimation(rotateAnimation);
这段代码的作用和第一种状态的动画类似,只不过这里我们用 RotateAnimation
类来实现小人旋转动画。
第三种状态的回弹
最后一种状态是松手后变回初始状态。
要实现这个动画,我们需要用到一个 TranslateAnimation
类。这个类可以让我们对小人进行平移动画。
// 创建 TranslateAnimation 对象
TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, -200);
// 设置动画的持续时间
translateAnimation.setDuration(300);
// 设置动画的重复次数
translateAnimation.setRepeatCount(Animation.INFINITE);
// 设置动画的重复模式
translateAnimation.setRepeatMode(Animation.REVERSE);
// 为小人添加动画
小人.startAnimation(translateAnimation);
这段代码的作用也和前面两种状态的动画类似,只不过这里我们用 TranslateAnimation
类来实现小人平移动画。
结语
以上就是美团下拉加载动画的实现方法。其实,实现这个动画并不难,只需要用到几个简单的动画类就可以了。