banner



How To Do Scale Animation In Xml

In the last two capacity, you learned near animation basics, including ii of the nearly common ways of writing animations on Android, ValueAnimator and ObjectAnimator. However, you lot have multiple ways to write animations in Android. Before wrapping up the first section of the book, you'll await at another handy way to create animations for views on Android: XML.

Why use XML animations?

In Chapter 1, "Value & Object Animators" and Chapter ii, "Animating Custom Views", you created animations purely in code. In the electric current chapter, you lot will replicate the aforementioned animations in XML. While having multiple options to create animations gives you more flexibility, it'south vital to understand the significance of XML animations so yous can make informed decisions when deciding which option to use.

Writing animations in XML makes your animation code reusable. Y'all merely demand to declare the core animation once, so utilise it for any view you want.

To bring consistency to the UX of your app, you lot want similar components to acquit in a similar, consistent manner beyond screens. Declaring animation behaviors once in XML makes achieving this consistency piece of cake.

Another bang-up advantage of XML-based animations is the power to swap out your animations with minimal effort. You only demand to alter the XML declaration instead of changing every instance of the blitheness implementation written in code.

That said, XML-based animations aren't a argent bullet. For one-off standalone animations, XML-based animations are a lot of work. In such scenarios, writing animations in code takes significantly less time.

With these insights, you can make more informed decisions about which implementation to choose.

Setting upwards the project

Open this affiliate'due south starter project in Android Studio. Build and run.

It's the same project y'all've worked on in previous chapters, but the animations accept been stripped out. In this chapter, you'll recreate the animations you lot added to the details screen in the first chapter using XML instead of Kotlin.

Writing your first view animation in XML

To kick things off, you'll animate the properties in the details screen. Right-click on the res binder and select New ▸ Android Resources Directory.

Next, create a new directory named anim.

Right-click on the newly created anim directory and select New ▸ Blitheness Resources File.

Finally, proper noun the XML file backdrop_animation. Skillful chore. You've at present created the file where yous'll write the definition for the properties's blitheness.

Start by calculation the following to backdrop_animation.xml:

          <?xml version="1.0" encoding="utf-eight"?> <translate    xmlns:android="http://schemas.android.com/apk/res/android"   android:duration="g"      android:fromYDelta="20%"   android:toYDelta="0%"       android:interpolator="@android:interpolator/decelerate_cubic" />                  

The animation instructions in this XML determine the transformations that will occur. Here's a breakup of what'due south going on in the snippet above:

  • translate: Defines which kind of transformation this blitheness volition utilise. When you define view animations in XML, the file must contain a single root tag, which can be an <alpha>, <scale>, <translate>, <rotate>, interpolator element or a <set> chemical element that holds groups of these elements.
  • android:duration: The duration of the animation in milliseconds. The elapsing will be 1000 which is equal to one second.
  • android:fromYDelta: The beginning position of the view on the y-axis. In this case, it has an showtime of 20% from its original position.
  • android:toYDelta: The stop position of the view on the y-axis. In this case, you want the view to go back to its original position, so it should take an offset of 0%.
  • android:interpolator: The interpolator to utilize for this animation. In this case, it'due south the decelerate interpolator.

Now that you've divers the animation semantics, it's time to plug in the information and make information technology play.

Playing the animation

Open MovieDetailsFragment.kt and supersede the //TODO in animateBackdrop() with the following:

          //1 val blitheness = AnimationUtils.loadAnimation(   requireContext(),   R.anim.backdrop_animation ) //two bounden.backdrop.startAnimation(blitheness)                  

Here's what'due south happening:

  1. Loads the animation file using AnimationUtils.loadAnimation().
  2. Starts the blitheness on the backdrop.

Build and run. You'll see the backdrop slide into place.

If you compare this method of creating the animation to what you did in the starting time chapter, you lot'll notice that you needed to write far less lawmaking here.

Learning the caveats of the view animation

While view animations are relatively straightforward to piece of work with and feel quite flexible, Google recommends confronting using them, in function considering their final beliefs can be deceptive.

Consider the translate animation y'all wrote above, and assume you wrote it for a push button. For at present, information technology works every bit you wait it to visually:

It translates the view from an commencement to its concluding position.

However, instead of moving the bodily view, it just translates its pixels — that is, its bitmap.

Notice that the push button is no longer clickable afterward the blitheness finishes because, while the button'southward bitmap moved to the concluding position, the push button still exists at the start position. This is deceptive nearly view animations. A view blitheness works neat for our groundwork, but would not be a adept pick for other elements in the layout like buttons.

At present that you've seen the well-nigh basic type of animation in Android and learned about its limitations, information technology's fourth dimension to accept a look at more than modern alternatives. Next you'll acquire about the Animator API, which includes derived classes ValueAnimator and ObjectAnimator.

Using ValueAnimator in XML

As the next footstep, you'll employ the ValueAnimator API in XML to animate the poster in the details screen.

Right-click on the res folder and select New ▸ Android Resource Directory and create a directory called Animator.

Then, right-click on Animator and select New ▸ Animator Resources File directory and name it poster_animation:

Supercede the existing code in the file with:

          <?xml version="1.0" encoding="utf-8"?> <animator      xmlns:android="http://schemas.android.com/apk/res/android"     android:elapsing="one thousand"     android:interpolator="@android:interpolator/overshoot"     android:valueFrom="0.0"     android:valueTo="1.0"     android:valueType="floatType" />                  

Hither's what you need to know nigh the snippet to a higher place:

  • animator: Declares a ValueAnimator in XML.
  • android:duration: The duration of the animation.
  • android:interpolator: The interpolator for this animation. In this case, you're using the overshoot interpolator.
  • android:valueFrom: The starting value of the animation.
  • android:valueTo: The end value of the blitheness.
  • android:valueType: The value blazon, which tin be either floatType or intType.

Now that you've defined ValueAnimator, it'due south fourth dimension to use it. Open MovieDetailsFragment.kt and supercede the //TODO in animatePoster() with the post-obit code:

          //i val animation =   AnimatorInflater.loadAnimator(     requireContext(),      R.animator.poster_animation   ) as ValueAnimator  animation.utilize {   //2   addUpdateListener { animation ->     val animatedValue = animation.animatedValue as Float     binding.posterContainer.alpha = animatedValue     binding.posterContainer.scaleX = animatedValue     bounden.posterContainer.scaleY = animatedValue   }   //3   start() }                  

Hither'south what this code does:

  1. Loads the animation using AnimatorInflater.loadAnimator(), and so casts it to a ValueAnimator. loadAnimator() returns an Animator object which is why the cast is needed.
  2. Adds updateListener to the animator and updates the alpha, scaleX and scaleY backdrop.
  3. Starts the animation.

Build and run. The poster now scales up and fades into identify when you launch the details screen.

So far in this chapter, you've created two resources directories, the anim and the animator directories. Here's how the two differ:

  • animator: Stores the XML files that define the property animation declarations: ValueAnimators and ObjectAnimatorsouthward.
  • anim: Stores the XML files that define the view animation declarations and tween animation declarations. Yous tin also store property animation declarations here, simply it'south better to store them separately in the animator directory so that the code is more than organized and it'due south piece of cake to tell the difference between the 2.

Using ObjectAnimator in XML

Side by side, you lot'll animate the movie summary text. This time, you'll leverage ObjectAnimator via XML to accomplish the effect.

Create a new file in the animator directory and proper noun information technology text_animation. Then, replace the existing code in the file with:

          <?xml version="1.0" encoding="utf-8"?> <objectAnimator      xmlns:android="http://schemas.android.com/apk/res/android"     android:duration="thou"     android:propertyName="alpha"     android:valueFrom="0.0"     android:valueTo="1.0"     android:valueType="floatType" />                  

Here are the important parts of the code higher up:

  • objectAnimator: Declares an ObjectAnimator in XML.
  • android:elapsing: The elapsing of the animation.
  • android:propertyName: The name of the property you're animative.
  • android:valueFrom: The starting value of the animation.
  • android:valueTo: The terminate value of the animation.
  • android:valueType: A value type that can be either floatType or intType.

Now that you've divers ObjectAnimator, it's fourth dimension to plug it in. Open MovieDetailsFragment.kt and replace the //TODO in the animateText() office with the following:

          //1 val textAnimation = AnimatorInflater.loadAnimator(   requireContext(),   R.animator.text_animation ) as ObjectAnimator //2 textAnimation.target = binding.summary //3 textAnimation.beginning()                  

Here'south the breakup of the snippet:

  1. Loads the animation using AnimatorInflater.loadAnimator().
  2. Sets the summary TextView as the target for the blitheness.
  3. Starts the animator.

Build and run. You'll now come across the summary text fade in when you launch the details screen.

And then far, you've animated unmarried properties, simply you might run into situations where y'all need to animate multiple properties of a view at one time. That's what you'll work on next.

Chaining multiple animations together

To chain multiple animations, you'll apply the AnimatorSet API. AnimatorSet lets you lot concatenation multiple animations and play them either in sequence or at once.

Correct now, the poster image uses an blithe value from ValueAnimator to animate the calibration and alpha properties. You lot'll switch its implementation to an AnimatorSet instead.

Create a new XML file in the animator directory and name information technology poster_animator_set. Then, add the following code to the file:

          <?xml version="1.0" encoding="utf-8"?> <!-- 1 --> <ready xmlns:android="http://schemas.android.com/apk/res/android"     android:ordering="together">      <!-- 2 -->     <objectAnimator         android:duration="1000"         android:interpolator="@android:interpolator/overshoot"         android:propertyName="alpha"         android:valueFrom="0f"         android:valueTo="1f" />      <!-- three -->     <objectAnimator         android:duration="grand"         android:interpolator="@android:interpolator/overshoot"         android:propertyName="scaleX"         android:valueFrom="0"         android:valueTo="1"         android:valueType="floatType" />     <!-- four -->     <objectAnimator         android:duration="yard"         android:interpolator="@android:interpolator/overshoot"         android:propertyName="scaleY"         android:valueFrom="0"         android:valueTo="i"         android:valueType="floatType" /> </set>                  

Here's what'southward happening:

  1. Yous use ready to declare an animator set up. android:ordering specifies the order in which the animator set's children will play. In this case, they'll play at the same time, or together.
  2. The starting time objectAnimator animates the alpha holding from 0 to 1.
  3. The second objectAnimator animates the scaleX property from 0 to one.
  4. The third objectAnimator animates the scaleY property from 0 to 1. All iii objectAnimatorsouth run for 1,000 milliseconds and use the overshoot interpolator.

Now that you've divers your animator set up, it's time to employ it. Open up MovieDetailsFragment.kt and replace the code in animatePoster() with the following:

          //1 val animation = AnimatorInflater.loadAnimator(   requireContext(),   R.animator.poster_animator_set ) every bit AnimatorSet  //2 blitheness.apply {   setTarget(binding.posterContainer)   start() }                  

The snippet you just added:

  1. Loads the animator using AnimatorInflater.loadAnimator() and casts it to an AnimatorSet.
  2. Sets the posterContainer view every bit the target for the AnimatorSet and starts the blitheness.

Build and run. The affiche should animate just like before, but with a new implementation under the hood.

Y'all've done a bang-up job recreating the animations so far. They look fantastic!

Now that you've wrapped up this chapter and the book's first department, you lot know how to breathing individual views and their corresponding backdrop. In the upcoming department, you'll learn about transitions and how to breathing entering and exiting a screen.

Fundamental points

  • Working with View animations tin can often create unexpected or broken behavior in your UI.
  • Animator APIs are a safer and more mod alternative to View Animations.
  • You store tween animation declarations and View animation declarations in the anim directory
  • You and then shop ValueAnimator declarations and ObjectAnimator declarations in the animator directory.
  • Employ AnimatorSet APIs to chain multiple animations.
  • Writing animations in XML makes them an first-class candidate for reuse beyond your projection.
  • The write-in one case-and-use-anywhere approach that XML animations offer makes the UX experience more consistent.
  • Since declarations alive in 1 identify, it'south easy to refactor them subsequently. Whatsoever changes you make are reflected everywhere the app uses the animations.

Source: https://www.raywenderlich.com/books/android-animations-by-tutorials/v1.0/chapters/3-xml-animations

Posted by: steinhoffcoth1963.blogspot.com

0 Response to "How To Do Scale Animation In Xml"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel