以下为Android常用的视图动画类,xml动画这里不做详解。
ScaleAnimation(缩放动画)可变化控件的大小
/** * Scale动画里x、Y指这个控件的宽高百分比,取值0~1 * * @param fromX 动画开始的X。 * @param toX 动画结束的X。 * @param fromY 动画开始的y。 * @param toY 动画结束的y。 * * @param 动画开始时X坐标类型,可以理解为从控件的哪个位置开始,下方动画同值。 * 取值范围为ABSOLUTE(绝对位置)、RELATIVE_TO_SELF(以自身宽或高为参考)、 * RELATIVE_TO_PARENT(以父控件宽或高为参考)。 * @param pivotXValue 取值0~1(1 is 100%) * @param pivotYType 动画开始时坐标类型 * 取值范围为ABSOLUTE(绝对位置)、RELATIVE_TO_SELF(以自身宽或高为参*考)、 * RELATIVE_TO_PARENT(以父控件宽或高为参考)。 * @param pivotYValue 取值0~1(1 is 100%) * 下面代码动画表示:从控件的左上角位置开始,放大1.5倍 */ val animation2 = ScaleAnimation(1f, 1.5f, 1f, 1.5f, ScaleAnimation.RELATIVE_TO_SELF, 0f, ScaleAnimation.RELATIVE_TO_SELF, 0f) animation2.duration = 700RotateAnimation
/** * 旋转动画 * @param fromDegrees 开始前角度 0代表当前无角度 * @param toDegrees 动画结束角度 * @param pivotXType * @param pivotXValue * @param pivotYType * @param pivotYValue * 下面代码动画表示:从控件的中心旋转360° */ val animation3 = RotateAnimation(0f, 360f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f)TranslateAnimation
/** * 平移动画 * @param fromXDelta 动画前X坐标 * @param toXDelta 动画结束X坐标 * @param fromYDelta 动画前Y * @param toYDelta 动画结束Y坐标 * 下面代码动画表示:从当前控件的起始位置0,向上Y移动100像素 */ var animation1 = TranslateAnimation(0f, 0f, 0f, -100f)AlphaAnimation
/** * 透明度动画 * @param fromAlpha 动画前View的通明度 * @param toAlpha 动画结束时View的通明度 */ val animation4 = AlphaAnimation(1f, 0.1f)AnimationSet组合动画,对View运行组合动画,这里需要注意AnimationSet中添加的动画是一起执行的,不能设定动画的先后执行顺序,同样也不能在动画的过程中进行操作。
/** * AnimationSet 有两个构造函数 * AnimationSet(Context context, AttributeSet attrs) // 传入一组动画属性attr(执行时间等) * AnimationSet(boolean shareInterpolator) // 是否共用插值器 * 注意事项: * 1.AnimationSet设定duration值(执行时长),会使集合中animation duration属性值失效 * 2.AnimationSet设定repeatCount值(重复次数)无效,只会取子动画设定值 * 3.AnimationSet设定repeatMode值(REVERSE从结束位置执行反动画,RESTART重新执行动画),会使子动画repeatMode无效 */ /** AnimationSet源码 */ class AnimationSet extends Animation { @Override public long getDuration() { final ArrayList<Animation> animations = mAnimations; final int count = animations.size(); long duration = 0; boolean durationSet = (mFlags & PROPERTY_DURATION_MASK) == PROPERTY_DURATION_MASK; if (durationSet) { //如果AnimationSet有设置duration,则取AnimationSet的duration duration = mDuration; } else { // 取子动画中最大的duration for (int i = 0; i < count; i++) { duration = Math.max(duration, animations.get(i).getDuration()); } } return duration; } } //使用方式 val animationTest = AnimationSet(true) animationTest.addAnimation(animation1) animationTest.addAnimation(animation2) animationTest.addAnimation(animation3) animationTest.addAnimation(animation4) animationTest.duration = 900 animationTest.interpolator = LinearInterpolator() //线性插值器