Z-Index conflict when animating fragment transition using the Android Navigation component

允我心安 提交于 2021-02-07 03:44:27

问题


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

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?


回答1:


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
        }
    }
}



回答2:


Unfortunately, this issue hasn't been resolved yet by Google. It has been reported here: https://issuetracker.google.com/issues/79443865

I struggle to understand how a company like Google is unable to provide something they tell us to do in their Material Guidelines.



来源:https://stackoverflow.com/questions/51337904/z-index-conflict-when-animating-fragment-transition-using-the-android-navigation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!