Android共享元素过渡动画

时间:2020-06-12 17:04:56

标签: android android-animation shared-element-transition

我正在使用共享元素过渡在整个活动中保持我的观点。我希望该视图在更改活动时执行一些动画(例如,翻转卡)。

换句话说,除了基本的共享转场(移动,缩放)以外,还执行其他动画

这可能吗?

1 个答案:

答案 0 :(得分:0)

这可以通过“自定义”过渡来完成,例如,翻转可以通过以下操作来完成:(用于ImageView,它使用transitionDrawable作为src来更改活动中的视图)

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.drawable.TransitionDrawable
import android.transition.Transition
import android.transition.TransitionValues
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView

class FlipTransition(ctx: Context, atts: AttributeSet): Transition(ctx, atts) {

    private val PROPNAME_DRAWABLE = "FlipTransition:drawable"

    private fun captureValues(transitionValues: TransitionValues) {
        val view = transitionValues.view
        if (view !is ImageView || view.getVisibility() != View.VISIBLE) {
            return
        }
        transitionValues.values[PROPNAME_DRAWABLE] = view.drawable
    }

    override fun captureStartValues(transitionValues: TransitionValues) {
       captureValues(transitionValues)
    }

    override fun captureEndValues(transitionValues: TransitionValues) {
        captureValues(transitionValues)
    }

    override fun createAnimator(
        sceneRoot: ViewGroup,
        startValues: TransitionValues?,
        endValues: TransitionValues?
    ): Animator? {

        if (startValues != null && endValues != null && endValues.view is ImageView) {
            val endView:ImageView = endValues.view as ImageView
            val startView:ImageView = startValues.view as ImageView

            val startAnim = ObjectAnimator.ofFloat(startView, "rotationY", 0F, 90F )
            startAnim.addListener(object: AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    startView.rotationY = 0F
                    (startView.drawable as TransitionDrawable).startTransition(300)
                }
            })

            val endAnim = ObjectAnimator.ofFloat(endView, "rotationY", 270F, 360F )
            endAnim.addListener(object: AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    (startView.drawable as TransitionDrawable).reverseTransition(300)
                }
            })

            return AnimatorSet().apply {
                play(startAnim).before(endAnim)
            };
        }

        return null
    }


}