📜  Android-动画(1)

📅  最后修改于: 2023-12-03 14:59:16.890000             🧑  作者: Mango

Android 动画

Android 中动画的实现可以让用户界面更加生动有趣,其中包括了视图动画和属性动画两种类型的动画。

视图动画

视图动画是一种简单的变换,通过改变视图的大小、位置、旋转和透明度等属性来实现动画效果。

平移动画

平移动画可以将视图沿 x、y 轴方向移动指定的距离。

TranslateAnimation translateAnim = new TranslateAnimation(0, 300, 0, 0); // 从左向右移动300个像素
translateAnim.setDuration(1000); // 设置动画持续时间
imageView.startAnimation(translateAnim); // 给 ImageView 加上动画效果
缩放动画

缩放动画可以将视图沿 x、y 轴方向缩放指定的比例。

ScaleAnimation scaleAnim = new ScaleAnimation(0.5f, 1.0f, 0.5f, 1.0f); // 缩放比例从0.5到1.0
scaleAnim.setDuration(1000); // 设置动画持续时间
imageView.startAnimation(scaleAnim); // 给 ImageView 加上动画效果
旋转动画

旋转动画可以将视图沿中心点旋转指定的角度数。

RotateAnimation rotateAnim = new RotateAnimation(0, 360, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); // 旋转360度
rotateAnim.setDuration(1000); // 设置动画持续时间
imageView.startAnimation(rotateAnim); // 给 ImageView 加上动画效果
透明度动画

透明度动画可以将视图的透明度从不透明到透明或从透明到不透明。

AlphaAnimation alphaAnim = new AlphaAnimation(1.0f, 0.0f); // 透明度从1.0到0.0
alphaAnim.setDuration(1000); // 设置动画持续时间
imageView.startAnimation(alphaAnim); // 给 ImageView 加上动画效果
属性动画

属性动画是 Android 新增的动画方式,可以通过改变视图的任意属性来实现动画效果。

基本用法
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "translationX", 0f, 300f); // 沿x轴平移300个像素
objectAnimator.setDuration(1000); // 设置动画持续时间
objectAnimator.start(); // 开始动画
多个动画同时执行
AnimatorSet animatorSet = new AnimatorSet(); // 初始化 AnimatorSet
ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageView, "translationX", 0f, 300f);
ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageView, "translationY", 0f, 300f);
ObjectAnimator animator3 = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f);
animatorSet.play(animator1).with(animator2).before(animator3); // 同时执行动画1和动画2,然后执行动画3
animatorSet.setDuration(1000); // 设置动画持续时间
animatorSet.start(); // 开始动画
动画监听器
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "alpha", 1.0f, 0.0f);
objectAnimator.setDuration(1000);
objectAnimator.addListener(new Animator.AnimatorListener() {
    @Override
    public void onAnimationStart(Animator animation) {
        // 动画开始时执行
    }

    @Override
    public void onAnimationEnd(Animator animation) {
        // 动画结束时执行
    }

    @Override
    public void onAnimationCancel(Animator animation) {
        // 动画被取消时执行
    }

    @Override
    public void onAnimationRepeat(Animator animation) {
        // 动画重复时执行
    }
});
objectAnimator.start();
总结

以上就是 Android 中动画的基本实现方法,使用动画可以让应用界面更加生动有趣,提升用户体验。需要注意的是,动画也会占用较多的系统资源,应该根据需要灵活使用。