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.
The only way I could avoid this was to not retain the fragment instance. In your DetailsFragment
's onCreate
method use setRetainInstance(false);
Android re-attaches existing fragment to an activity automatically in case of orientation change. 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:
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();
}
链接地址: http://www.djcxy.com/p/21170.html