Android system programming introduction series interface activity responds to silky traditional animation

Time:2021-10-17

Last articleThis paper introduces the relevant methods and locations of user operation response in the application. The simple response logic can be from an interfaceActivityJump to another interfaceActivity, or some viewsViewRelative changes in. However, whether you start an interface or execute a new interfaceActivityBoth the life cycle method and the relative change of the view take a period of time, so there is a blank time before the final result of the response is completed. In this long or short period of time, how to show the interface to the user? This uses the animation process recommended by the Android system.

Broadly speaking, the Android system can use relevant animation transition when the content drawn and displayed to users on the screen changes. Consistent with the response of user operation, the effect of displaying animation can act on the interface according to different action objects of animationActivity, can also act on viewsView。 Most articles are based on the introduction of frame animation and gap animation, which will be introduced separately according to the action object of animation.

View animation

View animation can work on any view that needs to display animation effectsView, view animation is the most native animation type of Android system, and the definition class of view animation can be viewedandroid.view.animation.Animation, its subclass is the effect classification of view animation, including gradient effectAlphaAnimation. rotation effectRotateAnimation, zoom effectScaleAnimation. movement effectTranslateAnimation, and a combined effect that brings the above multiple effects togetherAnimationSet

Due to viewViewIt can be declared statically in the layout file or dynamically registered in the code, so similarly, the declaration of view animation can also be divided into the layout fileStatic declaration, and in the codeDynamic declarationTwo ways. However, the effect of view animation needs to be determined according to different user responses, so it can only be used in the codeDynamic use。 Since view animation may contain a large amount of effect data, view animation is generally recommendedStatic declaration+Dynamic useThe way.

Dynamic declarationFor view animation effects, you only need to define the animation classes corresponding to the above five animation effects in the code and set relevant data parameters. among

Gradient effectAlphaAnimation (float fromAlpha, float toAlpha)You must set the fromalpha parameter as the starting transparency of the gradient effect and the toalpha parameter as the end transparency of the gradient effect.

Rotation effectRotateAnimation(float fromDegrees, float toDegrees, int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)You must set the fromdegrees parameter as the starting rotation angle of the rotation effect and the todegrees parameter as the end rotation angle of the rotation effect; Other parameters are optional, including the last four parameters in the form of screen coordinates. The pivotxtype parameter is the pivotxvalue parameter type, and the pivotxvalue parameter is the angle value of rotation around the X axis. Similarly, the pivotytype parameter is the pivotyvalue parameter type, and the pivotyvalue parameter is the angle value of rotation around the Y axis. The parameter types includeAnimation.ABSOLUTEAbsolute type, whose parameter value represents absolute value;Animation.RELATIVE_TO_SELFThe parameter value of the relative self view type is the percentage value of the relative self view before the animation effect;Animation.RELATIVE_TO_PARENTRelative parent view type, whose parameter value is the percentage value of the relative parent view before the animation effect.

Zoom effectScaleAnimation(float fromX, float toX, float fromY, float toY, int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)The parameters are also recorded in the form of screen coordinates. The fromx parameter must be set as the proportion in the x-axis direction at the beginning of the scaling effect, and the tox parameter as the proportion in the x-axis direction at the end of the scaling effect. Similarly, the fromy parameter is used as the proportion in the Y-axis direction at the beginning of the scaling effect, and the toy parameter is used as the proportion in the y-axis direction at the end of the scaling effect; Other parameters are optional, and their meaning is similar to the optional parameters of rotation effect.

Movement effectTranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)andTranslateAnimation(int fromXType, float fromXValue, int toXType, float toXValue, int fromYType, float fromYValue, int toYType, float toYValue)The parameters are also recorded in the form of screen coordinates. Either of the two construction methods can be selected. When the parameter value of type series in the eight parameter construction method isAnimation.RELATIVE_TO_SELFThe data represented by the value series parameters is consistent with the delta series parameters of the four parameter construction method.

Collection effectAnimationSet(boolean shareInterpolator)You can decide whether to use the interpolator defined in the current class object when displaying a series of animations in the animation according to the shareinterpolator parameter, and then you can call the interpolator of the objectaddAnimation(Animation a)Place the series view animation objects you want to execute in turn.

The interpolator mentioned here is implementedandroid.view.animation.InterpolatorInterface. These interpolator classes calculate the effect display from the beginning to the end of the view animation effect. In the above view animation effect animation object, you can callsetInterpolator(Interpolator i)Method setting. If it is not set, it will be used by defaultandroid.view.animation.LinearInterpolatorLinear interpolator.

Among the above five effect class construction methods, there is another one(Context context, AttributeSet attrs)Parameter, which can be used to pass in the statically declared animation resource file through parameter 2 attrs, so as to use the instantiated object in the code.

Static declarationThe view animation file must be saved inres/anim/A file in XML format in the resource directory. The root label of the file must be one of five view animation effects, including gradient effects. rotation effect, zoom effect. movement effect. collection effect。 The required and optional parameters are also related to the codeDynamic declarationCorresponding to in.

Finally, the instantiated objects of the above five view animation classes can be obtained in the code. Can callsetAnimationListener(Animation.AnimationListener listener)Set the monitoring of animation execution in the implementationandroid.view.animation.Animation.AnimationListenerInterface instances can be implemented separatelyonAnimationStart(Animation animation)Before the animation startsonAnimationRepeat(Animation animation)When the animation repeatsonAnimationEnd(Animation animation)Callback listening at the end of the animation. At the place where the animation display is started, callstartNow()The method can start immediately; Or call firstsetStartTime(long startTimeMillis)Set the delay time for startup, and then callstart()Method starts timing and displays the animation after the delay time.

Picture animation

Bitmap animation

In the system view provided by the Android SDK, there is a series of views similar to screen drawing images, such asandroid.widget.ImageView, this view with the function of drawing pixel bitmap is more suitable for drawing frame animation showing the continuous combination of multiple pictures. In essence, picture animation is just a combination of a series of pictures, so its declaration and use are more arbitrary, not only in the codeDynamic declaration+Dynamic useOr directly in the resource fileStatic declaration+Static use。 However, because image animation needs to load a large number of images, the method of dynamic declaration in the code is executed during the operation of the application, which may affect the user’s fluency. Therefore, it is recommended to use image animationStatic declaration+Static useThe way.

Dynamic declarationYour picture animation can be usedandroid.graphics.drawable.AnimationDrawableClass instantiates a frame animation composed of loading bitmaps. After that, the of the object is called in turnaddFrame(Drawable frame, int duration)Method to add each frame of picture to be displayed, including parameter 1frameThat is, the picture resource to be loaded is specified. Parameter 2durationIndicates the duration of the current picture resource frame in the whole animation playback, in millimeters. You can also call thesetOneShot(boolean oneShot)Sets whether the picture animation of the current series of frames is played only once. Finally, at the position where the image animation needs to be started, call thestart(), and at the position where you need to stop the picture animation, call the object’sstop()

It should be noted here that the image animation startsstart()Method must be in the interfaceActivityFinished executing the declaration cycle method ofonCreate()Then call.

Static declarationThe picture animation file must be saved inres/drawable/Directory, files in XML format. The root label of the file must be, which can be used in this labelandroid:oneshotThe attribute value istrueorfalseTo indicate whether the picture animation of the current series of frames is played only once. And each frame of the picture usesMediumandroid:drawableAttribute value asdrawableResource file reference, at the same time, throughandroid:durationThe attribute value sets the display duration of the current picture frame, which is usually set below 1000 (unit: ms) according to the recognition speed of human eyes. Then if you want toStatic use, you can animate the view by setting itsandroid:backgroudProperty and setStatic declarationResource file name asdrawableAssign a value to a resource type to be used in association. If you want toDynamic useFirst, find the object corresponding to the view to display the animation in the code, and call thesetBackgroundResource(int res), will alsoStatic declarationResource file name asR.drawableResource type assignment can also be used in association. Finally, in the code that needs to start the image animation, by calling thegetBackgroud()Method to obtain the interface of picture animationandroid.graphics.drawable.AnimatableObject, you can call it respectively where you need to start and stop the picture animationstart()andstop()method.

Vector graph animation

In addition, in Android 5.0, that is, API 21 and above, the project dependency library is added to the project modulesupport-vector-drawableandanimated-vector-drawable, to support the definition and drawing of vector graph in the resource file. When Android studio creates a default project, the default application icon used is the vector graph object. Its advantages are that the scaling is still undistorted and the volume is small, which will not be described in detail here. For this vector graph object, you can also add vector graph animation more quickly. Since vector graphics can only be statically declared in the resource file, corresponding vector graphics animation can only be declared in the resource fileStatic declaration。 This animation effect mainly depends onandroid.graphics.drawable.AnimatedVectorDrawableClass or the latest package is backward compatibleandroidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompatClass.

The declaration of vector graph is inres/drawable/Under the resource directory, clickThe layer wrapped by the label represents a common vector diagram, which can be added inside the labelThe label wraps a set of animation effects and sets itsandroid:nameAttribute marks the animation name of the group, and uses the view animation related attribute values as the display of view animation effects, including gradient, rotation, scaling and translation. You can alsoInside the label, continue to useThe label defines a series of paths, which also need to be setandroid:nameProperty to mark the group path name.

The declaration of vector animation is inres/animator/Under the resource directory, clickAnimate the root label wrap by setting itsandroid:propertyNameAttribute value, which can describe the effects of gradient, zoom, rotation and translation in the view animation effect. Its internal attributes are similar to those in the statically declared view animation. And withAs the root label, you can wrap a series of animation effects represented by the above four animation effectslabel.

Finally, it is necessary to associate the vector graph with the vector animationres/drawableCreate a new XML resource file in the resource directory toAs the root label and set itsandroid:drawableProperty and reference the above common vector graph resource file asdrawableResource type assignment. Pass within the root tagThey are in the definition of vector graphandroid:nameThe attribute value is associated with the resource file in the vector graph declaration. Finally, the reference to the common vector graph resource file is changed to the reference to the animation vector graph resource file.

Interface animation

Interface animation is only supported in Android 5.0, API 21 and above. Interface animation acts on the interfaceActivity, only in two interfacesActivityThe interface animation needs to be displayed only when switching is started. Therefore, the display objects of interface animation are mainly divided into three types, includingOld interfaceActivityAnimation effect on exit asNew interfaceActivityIf there are similar views of the same content between the animation effect and the two interfaces, it is calledShared view, its animation effect during interface switching. As for the animation effects of these objects, the Android SDK provides some unified animation effects to choose from, including fade in and fade out effects for exit and entry animationandroid.transition.FadeClass, movement effectandroid.transition.SlideClass I. explosion effectandroid.transition.ExplodeClass; There are also view animation effects for shared views. Or you can inheritandroid.transition.TransitionAchieve custom animation effects.

Due to the interfaceActivityThe definition of is statically registered in the manifest file, so the use of interface animation can also be used during registrationStatic declaration useThe way. It is used in static useStyle attribute whose value has been definedA style resource file in XML format for tags. stay< / code > the style label must contain the attribute < code > parent = "Android: theme. Material" < / code > or its sub style name</ p>
<p>To start the interface animation, first add a switch control to the style< br>
<code><item name="android:windowActivityTransitions">true</item></code><br>
Then rewrite the < code > < item > < / code > label in the style label, control different animation objects according to the < code > name < / code > attribute value, and specify different animation effects according to the < code > < item > < / item > < / code > label value. Here, the corresponding relation series of different animation objects are divided into the following table</ p>
<table>
<thead>
<tr>
< th > animated objects < / th >
< th > name value < / th >
</tr>
</thead>
<tbody>
<tr>
<td>Enter animation as a new interface</td>
<td>android:windowEnterTransition</td>
</tr>
<tr>
<td>Exit animation as old interface</td>
<td>android:windowExitTransition</td>
</tr>
<tr>
<td>Share view animation when entering as a new interface</td>
<td>android:windowSharedElementEnterTransition</td>
</tr>
<tr>
<td>Share view animation when exiting as old interface</td>
<td>android:windowSharedElementExitTransition</td>
</tr>
</tbody>
</table>
<br>
<p>Since the interface animation is statically declared through style definition, it can also be used through code < strong > Dynamic declaration in the method callback after the interface < code > activity < / code > is created. < a href is used here=“ https://developer.android.google.cn/reference/android/view/Window "Title =" Android. View. Window "target =" _blank "> Android. View. Window < / a > class. Because the style is modified before the interface loads the layout, before the < code > setcontentview() < / code > method, call < code > getwindow() The < / code > method can get the < code > window < / code > object</ p>
<p>First, you also need to call the < code > requestfeature (window. Feature_content_transitions) < / code > method of the object to turn on the interface animation switch< br>
After that, a series of methods of the object are called to control different animated objects, and different animation effects are specified according to the instance of the incoming <code>Transition</code> object. The corresponding relationships of different animation objects are shown in the following table</ p>
<table>
<thead>
<tr>
< th > animated objects < / th >
< th > window class calls method < / th >
</tr>
</thead>
<tbody>
<tr>
<td>Enter animation as a new interface</td>
<td>setEnterTransition()</td>
</tr>
<tr>
<td>Exit animation as old interface</td>
<td>setExitTransition()</td>
</tr>
<tr>
<td>Share view animation when entering as a new interface</td>
<td>setSharedElementEnterTransition()</td>
</tr>
<tr>
<td>Share view animation when exiting as old interface</td>
<td>setSharedElementExitTransition()</td>
</tr>
</tbody>
</table>
<br>
<p>For the animation of the shared view, you also need to mark the shared view in the two layout files respectively, and use the < code > Android: transitionname < / code > attribute to specify the same shared view name</ p>
<p>After declaring the animation effect of the interface, you also need to modify the original < code > startactivity (intent, bundle) < / code > method to < code > startactivity (intent, bundle) < / code > method at the position where the interface is started as a new interface or where the interface starts other interfaces as an old interface. The < code > intent < / code > parameter is also the intention information to start the interface before, and the < code > bundle < / code > parameter is the newly added data package to control the interface animation. You can obtain the interface animation effect declared by the current interface through the < code > activityoptions. Makescenetransitionanimation (this). Tobundle() < / code > series of methods, and the result value is used as < a href=“ https://developer.android.google.cn/reference/android/os/Bundle "Title =" Android. OS. Bundle "target =" _blank "> just pass in the Android. OS. Bundle < / a > object</ p>
<blockquote>
<p>If there is a single shared view animation in the interface animation, you can refer to the < code > activityoptions.makescenetransitionanimation (activity activity, view sharedelement, string sharedelementname) < / code > method</ p>
</blockquote>
<blockquote>
<p>If there are multiple shared view animations in the interface animation, you can refer to the < code > activityoptions.makescenetransitionanimation (activity, pair... < view, string > sharedelements) < / code > method</ p>
</blockquote>
<h2 id=""><br></h2>
<p>In addition to the above basic animation types acting on the three objects, the Android system also provides an attribute animation acting on any object. The animation has more comprehensive functions. For details, please look forward to the next article</ p>

Recommended Today

SQL statement of three-level linkage of provinces, cities and counties

The first is the table creation statement Copy codeThe code is as follows: CREATE TABLE `t_address_province` ( `id` INT AUTO_ Increment primary key comment ‘primary key’,`Code ` char (6) not null comment ‘province code’,`Name ` varchar (40) not null comment ‘province name’)Engine = InnoDB default charset = utf8 comment = ‘province information table’; CREATE TABLE […]