I’m using Google’s compat lib to enable fragments in my app (Target SDK 16, Min SDK 8) for devices running on 2.2+. From a functional point of view this runs all fine, but the performance of the view animations that are set up via
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(inTransition, outTransition, popInTransition, popOutTransition);
where inTransition is a simple translation like
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
<translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="@integer/animation_duration" />
</set>
and outTransition is a fade animation like
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="@integer/animation_duration" />
</set>
is just plain awful on my Galaxy S2 (4.0.3), i.e. for an animation that lasts about 350ms I’d say approx. half of the frames are dropped. I noticed that the performance gets a little (but not much) better if I disable the fade out, but then of course the complete effect of the animation is gone, because the origin fragment turns black instantly. I also tried a release version of the code, but the performance did not improve either.
What am I doing wrong? How can I make fragment animations smoother?
The first thing I’d recommend is enable hardware acceleration in the Manifest. This will only be enabled on devices with API 3.0+, but will significantly improve performance. With API 11 (3.0) and up, you can also take advantage of View LayerTypes. Set whatever you’re animating to
LAYER_TYPE_HARDWAREthen set it back toLAYER_TYPE_SOFTAREorLAYER_TYPE_NONEupon completion.Pre-honeycomb it becomes far more difficult. You don’t have hardware acceleration at all. You may be better off checking
if(api < 11) *use this animation* else *use this animation*. Sliding animations tend to work fairly smooth. Alpha animations are a burden on the CPU, especially when views have many layers. Apply any animation on the top-most parent view you can get away with (you’re animating entire fragments so it’s already happening).