简体   繁体   English

Android片段动画在方向更改时再次重复

[英]Android Fragment Animation is repeated again on Orientation Change

In my activity I have added the fragment by using the following code. 在我的活动中,我使用以下代码添加了片段。

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.right_to_left_in, R.anim.right_to_left_exit,R.anim.left_to_right_in,R.anim.left_to_right_exit);
DetailsFragment newFragment = DetailsFragment.newInstance();
ft.replace(R.id.details_fragment_container, newFragment, "detailFragment");
ft.commit();

Fragment is entering,exiting, popping with the animations properly. 片段正在正确进入,退出,弹出动画。 But when I orient the device, Fragment Manager is trying to add the fragment with the same animations. 但是当我定向设备时,片段管理器试图添加具有相同动画的片段。 It seems very odd. 看起来很奇怪。 I don't want the animation when user orients the device. 当用户调整设备方向时,我不需要动画。

I don't want to add onConfigChanges='orientation' in manifest since I want to change the fragment's layout design on orientation. 我不想在清单中添加onConfigChanges='orientation' ,因为我想更改片段的方向布局设计。

The only way I could avoid this was to not retain the fragment instance. 我可以避免的唯一方法是不保留片段实例。 In your DetailsFragment 's onCreate method use setRetainInstance(false); 在您的DetailsFragmentonCreate方法中,使用setRetainInstance(false);

Android re-attaches existing fragment to an activity automatically in case of orientation change. 如果方向发生变化,Android会自动将现有片段重新附加到活动中。 So you don't have to do it manually. 因此,您不必手动进行操作。 You may check savedInstanceState variable in onCreate method of the activity for null and replace a fragment with animation only in case if it's null: 您可以在活动的onCreate方法中检查saveInstanceState变量是否为null,并仅在动画为null的情况下用动画替换片段:

if (savedInstanceState == null) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.setCustomAnimations(R.anim.right_to_left_in, R.anim.right_to_left_exit,R.anim.left_to_right_in,R.anim.left_to_right_exit);
    DetailsFragment newFragment = DetailsFragment.newInstance();
    ft.replace(R.id.details_fragment_container, newFragment, "detailFragment");
    ft.commit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM