Replacing Fragment and adding layouts with animation in Android

    When replacing Fragments  in Activity or adding views to a container layout, we would like to use some animations in order to make this process smoothly. On the surface, Fragment transaction and inflating views are quite similar, the difference is each container layout (usally is a LinearLayout) can contains only one Fragment but unlimited on the number of view items.
   Now, I will present the way to resolve this requirement.

1. Create animation (xml) files

After starting a new Android project, in "res/anim" folder, put some animation files in it:


2. Create some layout (xml) files

Activity layout: contains 2 container layouts to replace fragment and adding views:

Fragment layout:
Inflated (child) layout:

3. Code code

In our Fragment, we random a number between [0;100] and show in TextView:

In Activity, we set event listener for 2 buttons which click them, a child layout was added to container layout or a Fragment was replaced (for more details, I commented in code):

4. Running program:



(sorry for having ads)

Share


Previous post
« Prev Post
Next post
Next Post »