Android Fragment Animation Repeats Again in Orientation Change

In my work, I added a snippet 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(); 

A fragment enters, exits, appears with animation correctly. But when I orient the device, Fragment Manager tries to add a fragment with the same animations. It seems very strange. I do not want animation when the user orientates the device.

I do not want to add onConfigChanges='orientation' to the manifest, since I want to change the fragment layout design to orientation.

+6
source share
2 answers

The only way to avoid this is to not save the instance of the fragment. In your DetailsFragment onCreate method, use setRetainInstance(false);

+3
source

Android automatically reconfigures an existing fragment in action in case of orientation change. Therefore, you do not need to do this manually. You can check the savedInstanceState variable in the onCreate method for an action for null and replace the fragment with animation only if it is 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(); } 
0
source

Source: https://habr.com/ru/post/971059/


All Articles