Android View动画
简介: 渐变、旋转、平移、伸缩四种基本动画。View动画是View的视觉效果变化,不会改变View原本的属性。即一个View平移后获取到的位置等都还会在原本的位置。也就导致了包括点击事件等,都会停留在原有的位置。
动画制作:
xml:
透明度动画
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="0" 起始渐变色
android:toAlpha="1" 最终渐变色>
</alpha>
旋转动画
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0" 起始旋转角度
android:pivotX="50%" 旋转中心点的X轴坐标
android:pivotY="50%" 旋转中心点的y轴坐标
android:toDegrees="360" 旋转最终角度>
</rotate>
缩放动画
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="1.0" 起始的x轴缩放比例
android:toXScale="0.5" 最终的x轴缩放比例
android:fromYScale="0.5" 起始的y轴缩放比例
android:toYScale="0.5" 最终的y轴缩放比例
android:pivotX="50%" 缩放的中心点的x轴坐标
android:pivotY="50%" 缩放的中心点的y轴坐标>
</scale>
平移动画
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0" 起始的x位置
android:fromYDelta="0" 起始的y位置
android:toXDelta="100%" 最终的x位置
android:toYDelta="100%" 最终的y位置>
</translate>
搭配以下属性使用(AndroidStudio不会自动联想,是默认继承自Animation的属性):
duration 动画持续时间
fillAfter 动画结束时,为true则View将保持动画结束时的状态
fillBefore 动画结束时,为true则View将还原到开始开始时的状态
repeatCount 动画重复执行的次数
repeatMode 动画重复模式 ,重复播放时restart重头开始,reverse重复播放时倒叙回放
interpolator 插值器,相当于变速器,改变动画的不同阶段的执行速度
注意: 在设置pivotX、pivotY、fromXDelta、fromYDelta、toXDelta、toYDelta等属性时,有三种设置值的方式。一种是直接的数值,如50,代表以View的左上角为起点,水平向右或垂直向下偏移50px。50%代表偏移View自身高度或宽度的50%。50%p代表View偏移View父类高度或宽度的50%(p就是parent)。
Java:
/**
* 透明度变化,变成100%-0%
* 旋转变化,0-360度,转一圈,旋转中心为x=0.5px,y=0.5px位置,支持设置0.5代表的含义,
* 可以设置绝对值(ABSOLUTE)/相对自身(RELATIVE_TO_SELF)/相对父类(RELATIVE_TO_PARENT),
* 分别代表含义50,50%,50%p。下面其他动画的属性也是一样,可以设置类型。
* 缩放变化,水平和垂直都从一般放大到完整。中心点为x=0.5px,y=0.5px位置,支持设置0.5代表的含义。
* 平移变化,从x轴和y轴都从0平移到100
*/
AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
RotateAnimation rotateAnimation = new RotateAnimation(0, 360, 0.5f, 0.5f);
ScaleAnimation scaleAnimation= new ScaleAnimation (0.5, 1, 0.5, 1, 0.5f, 0.5f);
TranslateAnimation translateAnimation = new TranslateAnimation (0,100,0,100);
//设置延时2000ms
animation.setDuration(2000);
监听
//可设置监听,支持开始、结束、重复的监听。
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// 动画开始
}
@Override
public void onAnimationEnd(Animation animation) {
// 动画结束
}
@Override
public void onAnimationRepeat(Animation animation) {
//动画重复
}
});
动画集制作
//四个动画一起播放
AnimationSet animationSet = new AnimationSet(true);
animationSet.addAnimation(alphaAnimation);
animationSet.addAnimation(rotateAnimation);
animationSet.addAnimation(scaleAnimation);
animationSet.addAnimation(translateAnimation);
animationSet.setDuration(2000);