支持片段弹出动画不起作用

4

我在我的应用程序中使用v4支持片段。我有一个活动,用户可以通过点击按钮查看更多信息。信息屏幕应该从底部滑上来,覆盖活动页面,当按下返回键时,向下滑动。目前我正在使用以下代码:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                    ft.setCustomAnimations(
                             R.anim.fragment_bottom_enter, 
                             R.anim.fragment_bottom_exit,                                  
                             R.anim.fragment_bottom_exit, 
                             R.anim.fragment_bottom_exit
                    );                 
                    ft.replace(R.id.fragmentContainer, fragment, TAG);
                    ft.addToBackStack(null);
                    ft.commit();

fragment_bottom_enter.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="500"
        android:fillAfter="true"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromYDelta="100%p"
        android:toYDelta="0%p" />
</set>

fragment_bottom_exit.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="500"
        android:fillAfter="true"
        android:fromYDelta="0%p"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toYDelta="100%p" />
</set>

上述代码可以实现进入动画(片段从底部滑入),但是弹出动画却没有播放。我甚至尝试了使用Android内置的淡入淡出动画,但都无济于事。希望能得到帮助解决这个问题。

提供更多细节关于 pop。你是如何调用 pop 的? - RamBabu Pudari
我没有从代码中调用pop。我将片段添加到backstack中,当按下返回按钮时,它会被弹出。 - Much Overflow
4个回答

1

虽然这个问题比较旧,但如果还有人像我一样遇到了这个问题,你需要使用 fragmentTransaction.add() 而不是 fragmentTransaction.replace() 来添加带有动画的碎片。


1

片段设置自定义动画方法是setCustomAnimations(int enter, int exit, int popEnter, int popExit)

  • enter: 片段进入动画。
  • exit: 片段退出动画,!注意:如果您调用replace并且有一个先前的片段,则先前的片段将运行此动画
  • popEnter: 当片段堆栈返回到片段时,它会运行此动画。
  • popExit: 当片段从片段堆栈中退出时,它会运行此动画。

因此,您应该这样调用它:

getSupportFragmentManager().beginTransaction()
    .setCustomAnimations(R.anim.slide_in_from_bottom, 0, 0, R.anim.slide_out_to_bottom)
    .replace(getFragmentId(), fragment, fragment.getClass().getSimpleName())
    .addToBackStack(fragment.getClass().getSimpleName())
    .commit();

希望它有所帮助。

1
我遇到了相同的问题,我注意到只有在片段容器视图(在你的情况下是R.id.fragmentContainer)没有固定的尺寸时才会发生这种情况,在我的情况下它的高度是wrap_content。将高度设置为固定值后,弹出动画就可以完美运行了。

0
在你的片段活动中,你需要重写onBackpress方法并像下面这样调用。
 @Override
  public void onBackPressed() {
    super.onBackPressed();
    getSupportFragmentManager().popBackStack();
}

然后你的片段可以从返回堆栈中弹出。


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