毫无疑问,动画效果能提高用户体验。我们平时使用最多的动画基本上是属性动画和补间动画了,属性动画很强,基本能定制我们想要的动画,但是你是否知道,API 21(5.0)后系统内置了Activity之间的切换动画,而且非常酷炫,今天我跟大家一起分享一下。我们知道,在两个Activity之间切换,我们一般会写出类似下面的代码:
Intent intent=new Intent(this,SecondActivity.class); startActivity(intent); overridePendingTransition(R.anim.enter_anim,R.anim.exit_anim);
在API 21以后,我们可以使用内置的Activity切换动画啦。但是这样也就意味着只能兼容5.0之后的系统,我们先看一个效果图来压压惊:
先看看第一个Activity,退出时用的是Explode效果,第二个Activity进入时用的是Slide效果。这些效果无需我们自己去实现,都是内置的效果,我们所编写的代码几乎为零,接下来我们一一看看内置了哪些效果。
ArcMotion arcMotion = new ArcMotion(); arcMotion.setMinimumHorizontalAngle(50f); arcMotion.setMinimumVerticalAngle(50f);
2.定义ChangeBounds类
我们自定义一个继承ChangeBounds的类,主要重写createAnimator函数,即创建你要执行的动画。这个函数由3个参数:
1.ViewGroup sceneRoot:屏幕根View,即DecorView,第二个Activity的DecorView。
2. TransitionValues startValues :属性动画的起始属性值,TransitionValues 对象内部有各Map类型的属性values,用于保存需要执行属性动画的属性。这个里面的属性值是在函数captureStartValues里放置,因此你可以重写captureStartValues函数,并把你自定义的属性动画中的属性放进去。
3. TransitionValues endValues :与startValues类似,表示属性动画结束时的属性值。可以通过重写captureEndValues函数,并把你自定义的属性动画里面的最终属性值放进去。
我们先看一个最简单的示例:
package com.hc.util;import android.animation.Animator;import android.transition.ChangeBounds;import android.transition.TransitionValues;import android.view.ViewGroup;import android.view.animation.AnimationUtils;public class CustomChangeBounds extends ChangeBounds {
@Override
public Animator createAnimator(final ViewGroup sceneRoot,
TransitionValues startValues, final TransitionValues endValues) {
Animator changeBounds = super.createAnimator(sceneRoot, startValues, endValues); if (startValues == null || endValues == null || changeBounds == null)
return null;
changeBounds.setDuration(300);
changeBounds.setInterpolator(AnimationUtils.loadInterpolator(sceneRoot.getContext(),
android.R.interpolator.fast_out_slow_in)); return changeBounds;
}
}