banner



How To Add Animations When Switching Between Views

Android'south transition framework allows you to breathing all kinds of move in your UI by merely providing the starting layout and the ending layout. You can select what type of blitheness y'all desire (such to fade the views in/out or alter the view sizes) and the transition framework figures out how to animate from the starting layout to the ending layout.

The transition framework includes the following features:

  • Group-level animations: Utilise one or more animation furnishings to all of the views in a view hierarchy.
  • Congenital-in animations: Utilize predefined animations for common effects such as fade out or movement.
  • Resource file support: Load view hierarchies and built-in animations from layout resource files.
  • Lifecycle callbacks: Receive callbacks that provide control over the blitheness and hierarchy change process.

For sample code that animates between layout changes, run across BasicTransition.

The bones process to animate between two layouts is as follows:

  1. Create a Scene object for both the starting layout and the ending layout. All the same, the starting layout'south scene is often determined automatically from the current layout.
  2. Create a Transition object to define what type of animation you want.
  3. Call TransitionManager.go() and the system runs the blitheness to bandy the layouts.

The diagram in figure 1 illustrates the relationship between your layouts, the scenes, the transition, and the final animation.

Figure 1. Basic illustration of how the transition framework creates an animation

Create a scene

Scenes store the state of a view bureaucracy, including all its views and their property values. The transitions framework can run animations betwixt a starting and an ending scene.

You can create your scenes from a layout resources file or from a group of views in your code. However, the starting scene for your transition is often determined automatically from the current UI.

A scene can besides ascertain its own actions that run when yous make a scene change. For example, this characteristic is useful for cleaning upwardly view settings after you transition to a scene.

Note: The framework tin animate changes in a single view hierarchy without using scenes, as described in Utilise a transition without scenes. However, understanding scenes is essential to work with transitions.

Create a scene from a layout resource

Y'all can create a Scene example directly from a layout resource file. Use this technique when the view bureaucracy in the file is mostly static. The resulting scene represents the country of the view hierarchy at the time you created the Scene instance. If you lot change the view bureaucracy, yous take to recreate the scene. The framework creates the scene from the entire view hierarchy in the file; you tin non create a scene from office of a layout file.

To create a Scene example from a layout resource file, call up the scene root from your layout every bit a ViewGroup case and then call the Scene.getSceneForLayout() function with the scene root and the resources ID of the layout file that contains the view hierarchy for the scene.

Ascertain layouts for scenes

The code snippets in the balance of this department prove you how to create two unlike scenes with the same scene root element. The snippets as well demonstrate that you can load multiple unrelated Scene objects without implying that they are related to each other.

The instance consists of the following layout definitions:

  • The main layout of an action with a text label and a child layout.
  • A relative layout for the first scene with ii text fields.
  • A relative layout for the 2d scene with the same ii text fields in different society.

The instance is designed so that all of the blitheness occurs within the child layout of the master layout for the action. The text label in the main layout remains static.

The main layout for the activity is defined as follows:

res/layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/master_layout">     <TextView         android:id="@+id/championship"         ...         android:text="Championship"/>     <FrameLayout         android:id="@+id/scene_root">         <include layout="@layout/a_scene" />     </FrameLayout> </LinearLayout>        

This layout definition contains a text field and a kid layout for the scene root. The layout for the first scene is included in the main layout file. This allows the app to display it as role of the initial user interface and also to load it into a scene, since the framework tin load only a whole layout file into a scene.

The layout for the start scene is defined as follows:

res/layout/a_scene.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/scene_container"     android:layout_width="match_parent"     android:layout_height="match_parent" >     <TextView         android:id="@+id/text_view1"         android:text="Text Line 1" />     <TextView         android:id="@+id/text_view2"         android:text="Text Line two" /> </RelativeLayout>        

The layout for the 2nd scene contains the same two text fields (with the aforementioned IDs) placed in a dissimilar guild and is defined as follows:

res/layout/another_scene.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/scene_container"     android:layout_width="match_parent"     android:layout_height="match_parent" >     <TextView         android:id="@+id/text_view2"         android:text="Text Line 2" />     <TextView         android:id="@+id/text_view1"         android:text="Text Line 1" /> </RelativeLayout>        

Generate scenes from layouts

After you lot create definitions for the 2 relative layouts, y'all can obtain a scene for each of them. This enables you lot to afterward transition betwixt the two UI configurations. To obtain a scene, you need a reference to the scene root and the layout resource ID.

The following lawmaking snippet shows you how to get a reference to the scene root and create two Scene objects from the layout files:

Kotlin

val sceneRoot: ViewGroup = findViewById(R.id.scene_root) val aScene: Scene = Scene.getSceneForLayout(sceneRoot, R.layout.a_scene, this) val anotherScene: Scene = Scene.getSceneForLayout(sceneRoot, R.layout.another_scene, this)            

Java

Scene aScene; Scene anotherScene;  // Create the scene root for the scenes in this app sceneRoot = (ViewGroup) findViewById(R.id.scene_root);  // Create the scenes aScene = Scene.getSceneForLayout(sceneRoot, R.layout.a_scene, this); anotherScene =     Scene.getSceneForLayout(sceneRoot, R.layout.another_scene, this);            

In the app, there are now 2 Scene objects based on view hierarchies. Both scenes employ the scene root defined by the FrameLayout chemical element in res/layout/activity_main.xml.

Create a scene in your code

You can also create a Scene instance in your lawmaking from a ViewGroup object. Utilize this technique when you change the view hierarchies directly in your code or when you generate them dynamically.

To create a scene from a view hierarchy in your code, use the Scene(sceneRoot, viewHierarchy) constructor. Calling this constructor is equivalent to calling the Scene.getSceneForLayout() function when you accept already inflated a layout file.

The post-obit lawmaking snippet demonstrates how to create a Scene case from the scene root element and the view hierarchy for the scene in your lawmaking:

Kotlin

val sceneRoot = someLayoutElement equally ViewGroup val viewHierarchy = someOtherLayoutElement as ViewGroup val scene: Scene = Scene(sceneRoot, viewHierarchy)            

Java

Scene mScene;  // Obtain the scene root element sceneRoot = (ViewGroup) someLayoutElement;  // Obtain the view hierarchy to add every bit a child of // the scene root when this scene is entered viewHierarchy = (ViewGroup) someOtherLayoutElement;  // Create a scene mScene = new Scene(sceneRoot, mViewHierarchy);            

Create scene actions

The framework enables yous to define custom scene deportment that the system runs when entering or exiting a scene. In many cases, defining custom scene actions is not necessary, since the framework animates the change between scenes automatically.

Scene actions are useful for handling these cases:

  • Animate views that are not in the aforementioned bureaucracy. Y'all tin can animate views for both the starting and ending scenes using exit and entry scene deportment.
  • Animate views that the transitions framework cannot animate automatically, such every bit ListView objects. For more information, come across Limitations.

To provide custom scene actions, define your deportment as Runnable objects and pass them to the Scene.setExitAction() or Scene.setEnterAction() functions. The framework calls the setExitAction() office on the starting scene before running the transition animation and the setEnterAction() office on the ending scene afterward running the transition animation.

Note: Practice not employ scene actions to pass information between views in the starting and catastrophe scenes. For more information, see Define transition lifecycle callbacks.

Apply a transition

The transition framework represents the style of animation between scenes with a Transition object. You tin instantiate a Transition using several built-in subclasses, such as AutoTransition and Fade, or ascertain your own transition. Then, you tin run the animation between scenes by passing your terminate Scene and the Transition to TransitionManager.go().

The transition lifecycle is like to the activity lifecycle, and it represents the transition states that the framework monitors between the start and the completion of an animation. At of import lifecycle states, the framework invokes callback functions that you can implement to make adjustments to your user interface at dissimilar phases of the transition.

Create a transition

In the previous section, you learned how to create scenes that stand for the state of dissimilar view hierarchies. Once you have divers the starting scene and the ending scene you lot want to change between, you demand to create a Transition object that defines an animation. The framework enables you lot to specify a built-in transition in a resource file and inflate it in your code or to create an example of a built-in transition directly in your code.

Table ane. Built-in transition types.

Class Tag Attributes Consequence
AutoTransition <autoTransition/> - Default transition. Fade out, motility and resize, and fade in views, in that social club.
Fade <fade/> android:fadingMode="[fade_in |
fade_out |
fade_in_out]"
fade_in fades in views
fade_out fades out views
fade_in_out (default) does a fade_out followed by a fade_in.
ChangeBounds <changeBounds/> - Moves and resizes views.

Create a transition instance from a resource file

This technique enables you lot to modify your transition definition without having to change the lawmaking of your activity. This technique is also useful to separate circuitous transition definitions from your application lawmaking, as shown in Specify multiple transitions.

To specify a congenital-in transition in a resource file, follow these steps:

  1. Add together the res/transition/ directory to your project.
  2. Create a new XML resource file inside this directory.
  3. Add an XML node for one of the built-in transitions.

For example, the following resource file specifies the Fade transition:

res/transition/fade_transition.xml

<fade xmlns:android="http://schemas.android.com/apk/res/android" />        

The following code snippet shows how to inflate a Transition instance inside your activeness from a resource file:

Kotlin

var fadeTransition: Transition =     TransitionInflater.from(this)                       .inflateTransition(R.transition.fade_transition)            

Java

Transition fadeTransition =         TransitionInflater.from(this).         inflateTransition(R.transition.fade_transition);            

Create a transition instance in your code

This technique is useful for creating transition objects dynamically if y'all alter the user interface in your code, and to create simple built-in transition instances with few or no parameters.

To create an case of a built-in transition, invoke one of the public constructors in the subclasses of the Transition class. For case, the following lawmaking snippet creates an example of the Fade transition:

Kotlin

var fadeTransition: Transition = Fade()            

Java

Transition fadeTransition = new Fade();            

Utilise a transition

You lot typically utilise a transition to change between unlike view hierarchies in response to an outcome, such as a user action. For example, consider a search app: when the user enters a search term and clicks the search button, the app changes to the scene that represents the results layout while applying a transition that fades out the search button and fades in the search results.

To make a scene change while applying a transition in response to some outcome in your activity, call the TransitionManager.go() grade function with the catastrophe scene and the transition instance to utilize for the animation, as shown in the post-obit snippet:

Kotlin

TransitionManager.go(endingScene, fadeTransition)            

Java

TransitionManager.go(endingScene, fadeTransition);            

The framework changes the view hierarchy inside the scene root with the view hierarchy from the ending scene while running the animation specified by the transition instance. The starting scene is the catastrophe scene from the last transition. If at that place was no previous transition, the starting scene is determined automatically from the current state of the user interface.

If you do not specify a transition example, the transition managing director tin can apply an automated transition that does something reasonable for most situations. For more information, see the API reference for the TransitionManager form.

Choose specific target views

The framework applies transitions to all views in the starting and ending scenes past default. In some cases, you may only desire to apply an animation to a subset of views in a scene. For instance, the framework does not support animating changes to ListView objects, and then y'all should not try to breathing them during a transition. The framework enables you to select specific views you want to animate.

Each view that the transition animates is called a target. You can merely select targets that are part of the view hierarchy associated with a scene.

To remove one or more than views from the list of targets, call the removeTarget() method before starting the transition. To add only the views yous specify to the listing of targets, call the addTarget() function. For more than information, see the API reference for the Transition form.

Specify multiple transitions

To get the nearly affect from an animation, you lot should match information technology to the type of changes that occur between the scenes. For example, if you are removing some views and adding others betwixt scenes, a fade out/fade in animation provides a noticeable indication that some views are no longer available. If you lot are moving views to different points on the screen, a better choice would be to breathing the motion then that users find the new location of the views.

You lot do non have to choose only ane animation, since the transitions framework enables you to combine blitheness effects in a transition set that contains a group of private built-in or custom transitions.

To define a transition ready from a collection of transitions in XML, create a resource file in the res/transitions/ directory and list the transitions nether the transitionSet chemical element. For example, the following snippet shows how to specify a transition gear up that has the same behavior as the AutoTransition class:

<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"     android:transitionOrdering="sequential">     <fade android:fadingMode="fade_out" />     <changeBounds />     <fade android:fadingMode="fade_in" /> </transitionSet>        

To inflate the transition prepare into a TransitionSet object in your lawmaking, call the TransitionInflater.from() office in your activeness. The TransitionSet class extends from the Transition class, then you tin apply information technology with a transition manager just like whatsoever other Transition case.

Employ a transition without scenes

Changing view hierarchies is not the but way to modify your user interface. You tin can also make changes by adding, modifying, and removing child views inside the current bureaucracy. For case, yous can implement a search interaction with just a unmarried layout. First with the layout showing a search entry field and a search icon. To modify the user interface to show the results, remove the search button when the user clicks it by calling the ViewGroup.removeView() function, and add together the search results past calling ViewGroup.addView() function.

You may desire to use this arroyo if the alternative is to have ii hierarchies that are nearly identical. Rather than having to create and maintain two separate layout files for a small-scale difference in the user interface, yous can accept one layout file containing a view hierarchy that you lot modify in lawmaking.

If y'all make changes within the current view hierarchy in this fashion, you do not need to create a scene. Instead, yous can create and use a transition between ii states of a view hierarchy using a delayed transition. This feature of the transitions framework starts with the current view hierarchy state, records changes y'all make to its views, and applies a transition that animates the changes when the system redraws the user interface.

To create a delayed transition within a single view hierarchy, follow these steps:

  1. When the upshot that triggers the transition occurs, telephone call the TransitionManager.beginDelayedTransition() part providing the parent view of all the views you want to modify and the transition to employ. The framework stores the electric current country of the child views and their holding values.
  2. Make changes to the child views as required by your use instance. The framework records the changes you make to the kid views and their properties.
  3. When the organisation redraws the user interface co-ordinate to your changes, the framework animates the changes between the original state and the new state.

The following example shows how to animate the addition of a text view to a view hierarchy using a delayed transition. The get-go snippet shows the layout definition file:

res/layout/activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/mainLayout"     android:layout_width="match_parent"     android:layout_height="match_parent" >     <EditText         android:id="@+id/inputText"         android:layout_alignParentLeft="truthful"         android:layout_alignParentTop="true"         android:layout_width="match_parent"         android:layout_height="wrap_content" />     ... </RelativeLayout>        

The next snippet shows the code that animates the improver of the text view:

MainActivity

Kotlin

setContentView(R.layout.activity_main) val labelText = TextView(this).use {     text = "Characterization"     id = R.id.text } val rootView: ViewGroup = findViewById(R.id.mainLayout) val mFade: Fade = Fade(Fade.IN) TransitionManager.beginDelayedTransition(rootView, mFade) rootView.addView(labelText)            

Java

private TextView labelText; private Fade mFade; private ViewGroup rootView; ...  // Load the layout setContentView(R.layout.activity_main); ...  // Create a new TextView and ready some View properties labelText = new TextView(this); labelText.setText("Label"); labelText.setId(R.id.text);  // Get the root view and create a transition rootView = (ViewGroup) findViewById(R.id.mainLayout); mFade = new Fade(Fade.IN);  // Start recording changes to the view hierarchy TransitionManager.beginDelayedTransition(rootView, mFade);  // Add the new TextView to the view hierarchy rootView.addView(labelText);  // When the organisation redraws the screen to show this update, // the framework volition animate the improver as a fade in            

Define transition lifecycle callbacks

The transition lifecycle is like to the action lifecycle. It represents the transition states that the framework monitors during the fourth dimension between a call to the TransitionManager.get() role and the completion of the blitheness. At important lifecycle states, the framework invokes callbacks defined by the TransitionListener interface.

Transition lifecycle callbacks are useful, for case, for copying a view property value from the starting view hierarchy to the ending view bureaucracy during a scene modify. Y'all cannot simply copy the value from its starting view to the view in the ending view hierarchy, because the ending view hierarchy is not inflated until the transition is completed. Instead, you need to store the value in a variable and so copy it into the ending view hierarchy when the framework has finished the transition. To get notified when the transition is completed, you can implement the TransitionListener.onTransitionEnd() function in your activeness.

For more than information, run across the API reference for the TransitionListener grade.

Limitations

This section lists some known limitations of the transitions framework:

  • Animations applied to a SurfaceView may not appear correctly. SurfaceView instances are updated from a non-UI thread, so the updates may exist out of sync with the animations of other views.
  • Some specific transition types may non produce the desired animation effect when practical to a TextureView.
  • Classes that extend AdapterView, such as ListView, manage their child views in ways that are incompatible with the transitions framework. If you endeavor to animate a view based on AdapterView, the device display may hang.
  • If you lot attempt to resize a TextView with an blitheness, the text volition pop to a new location earlier the object has completely resized. To avert this trouble, do non breathing the resizing of views that comprise text.

Source: https://developer.android.com/training/transitions

Posted by: davenportfortalwyneho.blogspot.com

0 Response to "How To Add Animations When Switching Between Views"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel