Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate fragment transition when fragments are loaded from XML

My tablet app has one activity and a few different layouts for different UI modes - each of these layouts uses < fragment > tags to populate the UI with different fragments (setContentView is called in the Activity to switch modes).

How can I use transition animations to fade-in the new fragments when they are being loaded this way? Right now switching between the modes produces a flicker effect as the fragments are loaded.

Thanks!

like image 576
hooby3dfx Avatar asked Nov 04 '22 09:11

hooby3dfx


1 Answers

I've never worked with fragments before, but there is no reason why having fragments would effect my solution. Basically, you implement an animation to be displayed on the first layout of something. The best example is a listview

First, you'll need to add a couple of extra animation files, added to res/anim

layout_controller.xml:

<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:delay="50%"
android:animation="@anim/bounce" />

This defines a process of laying something out.
Then, bounce.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/bounce_interpolator">
<translate
    android:fromXDelta="40%"
    android:toXDelta="0%"
    android:fromYDelta="0%"
    android:toYDelta="0%" 
    android:duration="900"/>
<alpha
    android:fromAlpha="0"
    android:toAlpha="1"
    android:duration="1000"
    android:interpolator="@android:anim/linear_interpolator"
    />

This animation will bounce the item in while also fading it in.

Now if you have a listview, set this in it's XML(would work for a textview, imageview, etc)

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:persistentDrawingCache="animation|scrolling"
android:layoutAnimation="@anim/layout_controller"
/>

the layoutAnimation field tells the listview to refer to layout controller on how to display the listview. When the listview is first drawn, each item should successively bounce in. You can easily customize the animation by changing bounce.xml or change the wait time by changing the 50% delay defined in layout_controller.

like image 73
Jameo Avatar answered Nov 11 '22 13:11

Jameo