Android - Custom Animation on fragment transaction not running
I'm using Google API 8 (Android 2.2) with support package v4.
It doesn't give any error or animation.
Transaction:
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.content, myFragment);
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
transaction.commit();
Animations:
slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="700"
android:fromXDelta="-100%"
android:toXDelta="0%" >
</translate>
</set>
slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="700"
android:fromXDelta="0%"
android:toXDelta="100%" >
</translate>
</set>
Does anyone know what is happening here?
The manager was stacking my transaction before I set the animation, so it stacks the transaction without animations (sad but true), and that occurs even if I commit the transaction after the setCustomAnimations()
.
The solution is to set the animations first:
FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
transaction.replace(R.id.content, myFragment);
transaction.commit();
As suggested above, separate statements will definitely work. But the trick here is to setCustomAnimation
before setting transaction type viz.add
, replace
, etc. else it doesn't. So, applying the same logic, method chaining
also works. eg.
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.a_slide_up,
R.anim.a_slide_down,
R.anim.a_slide_up,
R.anim.a_slide_down)
.add(R.id.root_layout,
MyFrag.newInstance())
.addToBackStack("MyFrag")
.commit();
Putting it here, so that someone who prefers method chaining
finds it helpful. Cheers!