使用Android导航组件为片段过渡设置动画时,Z索引冲突 [英] Z-Index conflict when animating fragment transition using the Android Navigation component

本文介绍了使用Android导航组件为片段过渡设置动画时,Z索引冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Android导航代替片段事务.然而,有一个问题开始变得麻烦.将滑入式动画用于 Enter Animation 时,新片段将位于当前片段下方.请务必查看以下视频以查看实际的错误.
https://youtu.be/gFnXiEyiypM

I'm trying to use Android Navigation instead of fragment transaction. There is one problem however which is starting to be cumbersome. Upon using a slide-in animation for the Enter Animation the new fragment goes beneath the current fragment. Be sure to check the following video to see the bug in action.
https://youtu.be/gFnXiEyiypM

该错误似乎并非来自 Navigation 组件,尽管该解决方案很笨拙()不会使用 Navigation 时似乎无法修复它.
在正式修复程序发布之前,没有解决方法吗?

The bug seems not to be from the Navigation component though the hacky solutions (this and this) which have been introduced for this specific problem doesn't seem to fix it when Navigation is used.
Isn't there a workaround for this until an official fix has been released?

推荐答案

只有在Google发布了正式的修复程序之后,该问题才有一个经过修正的修复程序.解决方案是使用以下代码覆盖 onCreateAnimation :

There is a hacky fix to this problem until an official fix has been released by Google. The solution is to override onCreateAnimation with this code:

class BaseFragment : Fragment() {

    override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
        if (nextAnim == R.anim.fragment_enter) {
            val nextAnimation = AnimationUtils.loadAnimation(context, nextAnim)
            nextAnimation.setAnimationListener(object : Animation.AnimationListener {
                private var startZ = 0f
                override fun onAnimationStart(animation: Animation) {
                    view?.apply {
                        startZ = ViewCompat.getTranslationZ(this)
                        ViewCompat.setTranslationZ(this, 10f)
                    }
                }

                override fun onAnimationEnd(animation: Animation) {
                    // Short delay required to prevent flicker since other Fragment wasn't removed just yet.
                    view?.apply {
                        this.postDelayed({ ViewCompat.setTranslationZ(this, startZ) }, 100)
                    }
                }

                override fun onAnimationRepeat(animation: Animation) {}
            })
            return nextAnimation
        } else {
            return null
        }
    }
}

这篇关于使用Android导航组件为片段过渡设置动画时,Z索引冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆