ser*_*tbh 4 android android-animation android-fragments
我想在打开和关闭时为片段设置动画。我有一个淡入和淡出自定义动画 XML 文件。
我在我的支持 FragmentTransaction 上使用 setCustomAnimations,但它所做的只是在我执行 addToBackStack 时进行动画处理,当我执行 popBackStack 时,它会在没有动画的情况下消失。
这是我的代码片段:
private void fragmentAppear(){
fragment = new LoginFragment();
fragmentManager = LoginActivity.this.getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
//my XML anim files
fragmentTransaction.setCustomAnimations(R.anim.slide_in_bottom,0,0,R.anim.slide_out_bottom);
fragmentTransaction.replace(R.id.login_fragment, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private void fragmentDisappear(){
getSupportFragmentManager().popBackStack();
}
Run Code Online (Sandbox Code Playgroud)
在 setCustomAnimations 部分,我使用了 4 个参数,到目前为止,当我调用 fragmentAppear 时,它只在滑入之前显示淡出动画,但在调用 fragmentDisappear 时从不显示。我已经尝试过以许多不同的方式对参数进行排序,我也尝试过使用 setCustomAnimations 的两个参数版本,它所做的只是在片段出现时进行动画处理。
我正在为我的片段使用 android.support.v4.app 库。
编辑:此外,在不调用 fragmentDisappear 的情况下按下后退按钮时,动画也不会显示。
过去的代码在活动中,我试图从片段中执行 popBackStack 并且它也不起作用。这是关闭我的片段的正确方法吗?
编辑:我将包括 XML 动画:
slide_in_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromYDelta="75%p"
android:toYDelta="0%p"
android:fillAfter="true"
android:duration="400" />
</set>
Run Code Online (Sandbox Code Playgroud)
slide_out_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromYDelta="0%p"
android:toYDelta="75%p"
android:fillAfter="true"
android:duration="400" />
</set>
Run Code Online (Sandbox Code Playgroud)
如果您查看代码,您将使用新片段替换该片段,但实际上是将 add 设置为 back stack null。为每个片段提供一个标签是一种很好的做法,甚至可以很容易地逐个标签找到该片段。将标签添加到您的片段中,如下所示。如果它仍然不起作用,那么问题将出在您的动画 xml 文件中。
private void fragmentAppear(){
fragment = new LoginFragment();
fragmentManager = LoginActivity.this.getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
//my XML anim files
fragmentTransaction.setCustomAnimations(
R.anim.slide_in_bottom,0,0,R.anim.slide_out_bottom);
fragmentTransaction.replace(
R.id.login_fragment, fragment, "loginFragment");
fragmentTransaction.addToBackStack("loginFragment");
fragmentTransaction.commit();
}
Run Code Online (Sandbox Code Playgroud)
从 Fragment Transaction 文档中,我看到了这个函数,你必须在那里指定适当的动画。
/**
* Set specific animation resources to run for the fragments that are
* entering and exiting in this transaction. The
* <code>popEnter</code>
* and <code>popExit</code> animations will be played for enter/exit
* operations specifically when popping the back stack.
*/
public abstract FragmentTransaction setCustomAnimations(@AnimRes int enter,
@AnimRes int exit, @AnimRes int popEnter, @AnimRes int popExit);
Run Code Online (Sandbox Code Playgroud)
玩这些直到你得到你想要的行为。
| 归档时间: |
|
| 查看次数: |
4195 次 |
| 最近记录: |