碎片、android:zAdjustment(Z轴顺序)和动画

25

我正在使用支持库。现在,我想要一个从底部移入并覆盖上一个片段的片段。

为此,我使用以下代码使之前的片段(正在被滑动遮盖的那个)保持可见,直到新的片段到位:

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
   android:fromAlpha="1.0" android:toAlpha="1.0" 
   android:duration="2500"
   android:zAdjustment="bottom" />

这是用于使新的Fragment从底部滑入的动画:

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="100%p" android:toYDelta="0"
        android:duration="@android:integer/config_mediumAnimTime" 
        android:zAdjustment="top"/>

我已经针对两者都将Z调整设置为底部和顶部,但仍然发现“底部”动画仍在新片段的上方!我已将持续时间设置为2500进行测试,但它在整个时间内都保持在顶部。

对于片段动画,zAdjustment不起作用吗?


你找到任何方法强制使前一个片段出现在当前片段下面了吗? - Guillaume Boudreau
我不确定我做了什么才让它工作。应该检查我的代码,但现在不可能。 - Boy
1
你能否在片段动画中调整z-index?如果您能与我们分享,那将非常有帮助。 - cprcrack
我遇到了类似的问题。你找到了改变Z顺序的方法,以便出现的片段在.replace()转换期间处于顶部吗? - Moritz
对不起,我不知道我是怎么陷入这种情况的。对我来说已经太久了。 - Boy
4个回答

9
根据这个谷歌论坛帖子,Z调整仅适用于窗口动画。
“Z调整仅适用于窗口动画。我认为这已经有文档记录了,但显然并没有。” -- Dianne Hackborn(Android框架工程师)

6

你可以重写onCreateAnimation方法,在任何动画中,你可以检查当前正在运行的动画,并且如果需要将其置于顶部,则可以从那里设置Z轴。

override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
    if (nextAnim == R.anim.enter_from_right || nextAnim == R.anim.exit_to_right) {
        ViewCompat.setTranslationZ(view, 1f)
    } else {
        ViewCompat.setTranslationZ(view, 0f)
    }

    return super.onCreateAnimation(transit, enter, nextAnim)
}

建议将此作为所有片段的基本片段类来实现。


在我的Fragment中,view始终为null。 - advice
这仅适用于Android 21+。对于其他版本,setTranslationZ无效。 - Vsevolod Ganin
return super.onCreateAnimation(transit, enter, nextAnim) throw java.lang.IllegalStateException: super.onCreateAnimation(transit, enter, nextAnim) must not be null better to make return AnimationUtils.loadAnimation(context, nextAnim) - Yuri Misyac

4
我也曾经遇到过这个问题。所以,我创建了两个用于片段的容器,而不是使用 transaction.replace(containerId, newFragment)。现在我的代码看起来像下面这样:
添加第一个片段:
transaction.add(containerId1, firstFragment).commit();

在第一个片段上添加带有动画效果的第二个片段:
findViewById(containerId2).bringToFront();
transaction.setCustomAnimations(R.anim.slide_in_up,
 R.anim.stay).remove(oldFragment).add(containerId2, newFragment).commit()

1
你可以使用androidx.fragment.app.FragmentContainerView作为片段容器。它会自动处理在setCustomAnimations()中指定的动画的z顺序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接