首页 > 解决方案 > 动画结束不平滑过渡到新图像

问题描述

我有一个图像视图,它根据状态显示向上/向下箭头BottomSheet,我正在尝试为箭头设置动画,使其看起来更好,但在动画结束时它不会平滑过渡到新图像。我看到旧图像大约有一毫秒,直到它切换到更新的图像。

这是我的代码

private val bottomSheetCallback = object:BottomSheetBehavior.BottomSheetCallback(){
        override fun onSlide(p0: View, p1: Float) {}

        /**
         * Listen to state changes of the bottom sheet
         */
        @SuppressLint("SwitchIntDef")
        override fun onStateChanged(p0: View, state: Int) {
            when(state){
                BottomSheetBehavior.STATE_COLLAPSED -> startRotateAnimation()
                BottomSheetBehavior.STATE_EXPANDED -> startRotateAnimation()
            }
        }

        private fun startRotateAnimation(){
            val rotateAnimation:RotateAnimation = RotateAnimation(0f,180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
            rotateAnimation.duration = 500
            rotateAnimation.setAnimationListener(object : Animation.AnimationListener {

                override fun onAnimationStart(animation: Animation?) {
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {
                    when(_scannedBarcodesList.state){
                        BottomSheetBehavior.STATE_COLLAPSED -> expand.setImageResource(R.drawable.ic_keyboard_arrow_up_24px)
                        BottomSheetBehavior.STATE_EXPANDED -> expand.setImageResource(R.drawable.ic_keyboard_arrow_down_24px)
                    }
                }
            })
            expand.startAnimation(rotateAnimation)
        }
    }

我正在尝试将图像旋转 180 度(例如向上箭头指向下方),然后在动画结束时实际将图像视图切换到向下箭头,但就像我说的那样,动画似乎在图像更改显示之前结束向上箭头一毫秒,所以它看起来很糟糕。

如何在图像切换之前摆脱动画结束?

标签: androidandroid-animation

解决方案


当动画结束导致 UI 卡顿时,您正在更改图像。

试试这个方法

public static void rotateView(ImageView iv, int stateOfBottomSheet){
        RotateAnimation rotateAnimation;
        if(stateOfBottomSheet == BottomSheetBehavior.STATE_COLLAPSED){
            rotateAnimation = new RotateAnimation(180.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        }else {
            rotateAnimation = new RotateAnimation(0.0f,180.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        }
        rotateAnimation.setInterpolator(new DecelerateInterpolator());
        rotateAnimation.setRepeatCount(0);
        rotateAnimation.setDuration(300);
        rotateAnimation.setFillAfter(true);
        iv.startAnimation(rotateAnimation);
    }

推荐阅读