Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does android Material Design create a new animation

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "android Material Design how to create a new animation", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "android Material Design how to create a new animation" article.

Animation in Material Design will provide users with operational feedback and visual continuity as they interact with your application. Material Design will provide some default animations for button and action behavior transitions, while Android 5.0 (API Level 21) and later will allow you to customize these animations and create new ones:

First, touch feedback animation

Effect picture:

Material Design's touch feedback provides instant visual confirmation at the point of contact when the user interacts with the UI element. The default touch animation for buttons uses a new RippleDrawable category to convert between different states with ripple effects.

In most cases, the view background should be specified in the following ways, and this feature is applied in your view XML:

Android:attr/selectableItemBackground specifies bounded ripples.

Android:attr/selectableItemBackgroundBorderless specifies the ripple that crosses the view boundary. It will be drawn and bounded by the nearest parent of a view with a non-empty background.

Any view that is clickable can use RippleDrawable to achieve ripple effects, and it must be clickable for ripple animation to occur.

You can set this in your code:

Note: selectableItemBackgroundBorderless is a new attribute introduced in API Level 21.

In addition, you can use the ripple element to define RippleDrawable as a XML resource.

You can specify a color for the RippleDrawable object. If you want to change the default touch feedback color, use the android:colorControlHighlight property of the theme.

For more information, see the API reference documentation for the RippleDrawable category.

Let's take a look at how the touch feedback animation that comes with the system is realized. Why do you only need to set the background or foreground property of view to? android:attr/selectableItemBackground or? android:attr/selectableItemBackgroundBorderless to achieve the effect of ripple animation? Click on these two attributes, and you can see that these two attributes are defined in the path sdk/platforms/android-xx/data/res/values/attrs.xml file:

We think that since these two attributes are valid in the entire app, they may be attributes in Theme, so go to the AndroidManifest file and follow the Theme step by step. * you can see that there are indeed these two item attributes in the style of Base.V21.Theme.AppCompat.Light:

? android:attr/selectableItemBackground? android:attr/selectableItemBackgroundBorderless

But here is still the defined property of the called system, continue to follow, in android:Theme.Material and android:Theme.Material.Light, you can see:

@ drawable/item_background_material @ drawable/item_background_borderless_material

Then platforms\\ android-xx\\ data\\ res\\ drawable under the sdk path can find these resource files as shown below:

The content of item_background_material is:

The content of item_background_borderless_material is:

The system defines RippleDrawable as a XML resource with the ripple element, and the background attribute is obtained in the constructor by looking at the source code of View:

Public View (Context context, @ Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {this (context); final TypedArray a = context.obtainStyledAttributes (attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); if (mDebugViewAttributes) {saveAttributeData (attrs, a);} Drawable background = null Switch (attr) {case com.android.internal.R.styleable.View_background: background = a.getDrawable (attr); break;. . . }

In other words, this background is actually the RippleDrawable class. Then let's take a look at how this RippleDrawable is done inside.

First of all, the official document explains to RippleDrawable that

Drawable that shows a ripple effect in response to state changes. The anchoring position of the ripple for a given state may be specified by calling setHotspot (float, float) with the corresponding state attribute identifier.

In response to a change in the state by displaying the ripple effect, the anchoring position of the ripple for a given state can be specified by calling setHotspot (float,float) with a corresponding state attribute identifier.

RippleDrawable inherits from LayerDrawable, and LayerDrawable inherits Drawable,RippleDrawable in response to View's statechange, so take a look at the state handling of clicks in the Drawable class.

Public boolean setState (@ NonNull final int [] stateSet) {if (! Arrays.equals (mStateSet, stateSet)) {mStateSet = stateSet; return onStateChange (stateSet);} return false;}

When you set the state property to Drawable, you pass an array of states to the onStateChange method, overriding onStateChange in RippleDrawable.

When you see setRippleActive and setBackgroundActive, you should be able to guess what they mean. Go on.

Private void setRippleActive (boolean active) {if (mRippleActive! = active) {mRippleActive = active; if (active) {tryRippleEnter ();} else {tryRippleExit ();}

If Drawable is enable=true and pressd=true, the tryRippleEnter method is called

Seeing here, we can know the effect of starting to do ripple animation. MRipple is an instance of the RippleForeground class, but I didn't find the setup and enter methods in the RippleForeground class, but RippleForeground inherits from the RippleComponent class, so I found these two methods in this class.

Public final void setup (float maxRadius, int densityDpi) {if (maxRadius > = 0) {mHasMaxRadius = true; mTargetRadius = maxRadius;} else {mTargetRadius = getTargetRadius (mBounds);} mDensityScale = densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE; onTargetRadiusChanged (mTargetRadius);}

Setup initializes a series of parameters, and enter creates an animation and starts the animation.

As you can see from the above code that creates the animation, it is actually a combined attribute animation, and then customizes the three attribute ripple radius TWEEN_RADIUS, ripple center point TWEEN_ORIGIN, and ripple opacity OPACITY. A composite animation is obtained through the transitional changes of these three attributes. The above is the realization process of foreground ripple animation effect.

Private void setBackgroundActive (boolean active, boolean focused) {if (mBackgroundActive! = active) {mBackgroundActive = active; if (active) {tryBackgroundEnter (focused);} else {tryBackgroundExit ();}}

MBackground is an instance of the RippleBackground class, and unlike RippleForeground, the background animation simply changes the opacity.

@ Override protected Animator createSoftwareEnter (boolean fast) {/ / Linear enter based on current opacity. Final int maxDuration = fast? OPACITY_ENTER_DURATION_FAST: OPACITY_ENTER_DURATION; final int duration = (int) ((1-mOpacity) * maxDuration); final ObjectAnimator opacity = ObjectAnimator.ofFloat (this, OPACITY, 1); opacity.setAutoCancel (true); opacity.setDuration (duration); opacity.setInterpolator (LINEAR_INTERPOLATOR); return opacity;}

The above analysis is the enter ripple animation generated when the finger touches the view. When the finger is raised, the state will also change, resulting in an exit animation, so we will not analyze it in detail here.

Second, the use of disclosure effect

Effect picture:

When you need to show or hide a set of UI elements, expose the animation to provide visual continuity for the user.

/ * @ param view The View will be clipped to the animating circle. View * @ param centerX The x coordinate of the center of the animating circle, relative to view. The center point of the beginning of the animation X * @ param centerY The y coordinate of the center of the animating circle, relative to view. The center point of the animation is Y * @ param startRadius The starting radius of the animating circle. Animation start radius * @ param endRadius The ending radius of the animating circle. Animation end radius * / public static Animator createCircularReveal (View view, int centerX, int centerY, float startRadius, float endRadius) {return new RevealAnimator (view, centerX, centerY, startRadius, endRadius);}

RevealAnimator is no different from the previous animation, you can also set up listeners and accelerators to achieve a variety of special effects, the animation is mainly used to hide or show a view, change the size of the view and other transition effects.

Display view:

Final TextView tv9 = (TextView) findViewById (R.id.tv9); findViewById (R.id.content_main) .setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {/ / get the center for the clipping circle int cx = (tv9.getRight ()-tv9.getLeft ()) / 2; int cy = (tv9.getBottom ()-tv9.getTop ()) / 2 / get the final radius for the clipping circle int finalRadius = Math.max (tv9.getWidth (), tv9.getHeight ()); / / create the animator for this view (the start radius is zero) final Animator anim = ViewAnimationUtils.createCircularReveal (tv9, cx, cy, 0, finalRadius); tv9.setVisibility (View.VISIBLE); anim.start ();}})

Hide view:

Final TextView tv9 = (TextView) findViewById (R.id.tv9); tv9.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {/ / get the center for the clipping circle int cx = (tv9.getRight ()-tv9.getLeft ()) / 2; int cy = (tv9.getBottom ()-tv9.getTop ()) / 2 / / get the final radius for the clipping circle int initRadius = Math.max (tv9.getWidth (), tv9.getHeight ()); / / create the animator for this view (the start radius is zero) final Animator anim = ViewAnimationUtils.createCircularReveal (tv9, cx, cy, initRadius, 0) Anim.addListener (new AnimatorListenerAdapter () {@ Override public void onAnimationEnd (Animator animation) {super.onAnimationEnd (animation); / / make the view visible and start the animation tv9.setVisibility (View.INVISIBLE);}}); anim.start ();}})

Zoom out along the center:

Animator animator = ViewAnimationUtils.createCircularReveal (view, view.getWidth () / 2, view.getHeight () / 2, view.getWidth (), 0); animator.setInterpolator (new LinearInterpolator ()); animator.setDuration (1000); animator.start ()

Expand from the upper left corner:

Animator animator = ViewAnimationUtils.createCircularReveal (view,0,0,0, (float) Math.hypot (view.getWidth (), view.getHeight (); animator.setDuration (1000); animator.start ()

Third, use transition animation

The effect takes the transition animation of a shared element as an example:

Operational behavior transformations in MaterialDesign applications provide visual connections between different states through movements and transitions between common elements. You can specify custom animation for shared element transformations between entry, exit transformations, and action behaviors. Before 5. 0, we can call overridePendingTransition after startActivity to specify the transition animation of Activity.

Entering the transformation determines how the view in the action behavior enters the scene. For example, in the decomposition into transformation, the view enters the scene from outside the screen and flies to the center of the screen.

Exiting the transformation determines how the display view of the applied behavior in the action behavior exits the scene. For example, in an explode exit transformation, the view exits the scene from the center of the screen.

Shared element transformations determine how views shared between two action behavior transformations are transformed in these action behaviors. For example, if two actions have the same image, but their location and size are different, the changeImageTransform shared element transformation will smoothly convert and scale the image between those actions.

Android 5.0 (API Level 21) supports these entry and exit transformations: (normal transition animation)

Explode-moves in or out of the view from the center of the scene.

Slide-move in or out of the view from the edge of the scene.

Fade in and out-add or remove views from the scene by adjusting transparency.

These shared element transformations are also supported: (transition animation of shared elements)

ChangeBounds-adds animation to the size of the target view.

ChangeClipBounds-adds animation to the crop size of the target view.

ChangeTransform-animates the zoom, rotation, and displacement of the target view.

ChangeImageTransform-animates the scaling, rotation, and displacement of the target picture.

Specify transition animation

To use the new transition animation, you can inherit the Material Design theme and specify it in the style style:

Change_image_transform is defined as follows:

If you want to open the window content conversion in the code, you need to call the Window.requestFeature () method.

Normal transition animation:

All inherits from the visibility class can be used as excessive animation for entry and exit. If we want to customize the animation of entry and exit, we only need to inherit Visibility, overload the onAppear and onDisappear methods to define the animation of entry and exit. The system provides three default methods:

Explode moves in or out of the view from the center of the screen

Slide moves in or out of view from the edge of the screen

Fade changes the transparency of the view

If you want to specify custom excessive animation of entry and exit in xml, you need to define the animation first:

Note: where CustomTransition is our custom animation, it must be inherited from Visibility.

To start an Activity in a normal transition animation, you must pass a Bundle object of ActivityOptions in the startActivity function:

ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation (activity); startActivity (intent, options.toBundle ())

If you want the return to have a transition effect, instead of calling the finish function in the returned Activity, you should ask finishAfterTransition to end an Activity, which waits for the animation to finish before ending the Activity.

Share the transition animation:

If you want to use transition animation between two Activity with shared elements, then:

1. Enable window content conversion in the question. Android:windowContentTransitions

2. Specify a shared element transformation in Theme.

3. Define transitions as a xml resource.

4. Use the android:transitionName attribute to specify a common name for the shared elements in the two layouts.

Use the ActivityOptions.makeSceneTransitionAnimation () method.

/ / get the element that receives the click event final View imgContainerView = findViewById (R.id.img_container); / / get the common element for the transition in this activity final View androidRobotView = findViewById (R.id.image_small); / / define a click listener imgContainerView.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View view) {Intent intent = new Intent (this, Activity2.class) / / create the transition animation-the images in the layouts / / of both activities are defined with android:transitionName= "robot" ActivityOptions options = ActivityOptions .makeSceneTransitionAnim ation (this, androidRobotView, "robot"); / / start the new activity startActivity (intent, options.toBundle ());}})

If you want to generate a shared view in your code, you need to call the View.setTransitionName () method to specify a common name for the shared elements in both layouts.

If you have more than one shared element, you can wrap it through Pair:

ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation (activity, Pair.create (view1, "name1"), / / if view1 or view2 are TextView or ImageView, you need to convert to View before you can Pair.create (view2, "name2"); startActivity (intent,.toBundle ())

If you need to have a transition animation when you return, you also need to use the finish function instead of finishAfterTransition to end an Activity.

Use curvilinear motion

Because curve motion is mixed with attribute animation and Bezier curves, I'm going to write this section separately. I won't say much here.

View state change

Android 5.0has been enhanced on the original picture selector and color picker, not only the control can display different background pictures according to different states, but also can specify an animation when switching between the two states, to increase the transition effect, attract users' attention, and highlight the key content.

The StateListAnimator class is similar to the image selector and the color selector, which can present different animation effects according to the state changes of view. Through xml, we can build animation collections corresponding to different states. The way to use it is also very simple. You can specify an attribute animation in the corresponding state:

This can be loaded in the code:

TextView tv11 = (TextView) findViewById (R.id.tv11); StateListAnimator stateLAnim = AnimatorInflater.loadStateListAnimator (this,R.drawable.selector_for_button); tv11.setStateListAnimator (stateLAnim)

After inheriting the Material theme, the button has the z property animation by default. If you want to cancel this default state, you can specify the state animation as null.

In addition to the attribute animation of the state switch specified by the StateListAnimator class, you can also specify the frame animation of the state switch through AnimatedStateListDrawable:

The resource file for frame animation can be used as the background of view directly in xml.

IV. Vector animation

Effect picture:

First define a vector graph in drawable:

Then define the animation in anim:

* define an animated-vector in drawable: a vector graph that assigns animation resources to the value of the drawable attribute.

Note: here the drawable attribute value is the vector image we defined earlier. The name in target should be the same as the name of path in the vector diagram, and animation is the animation resource file defined earlier.

Use it in xml in view and start animation in your code:

ImageView iv = (ImageView) findViewById (R.id.iv); Drawable drawable = iv.getDrawable (); if (drawable instanceof Animatable) {((Animatable) drawable). Start ();} the above is about "how to create a new animation in android Material Design". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about it, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report