Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 32  Property Animation


All of these properties have getters and setters. For example, if you wanted to know the current
value of translationX, you would call getTranslationX(). If you wanted to set it, you would call
setTranslationX(float).


So what does the y property do? The x and y properties are conveniences built on top of local layout
coordinates and the transformation properties. They allow you to write code that simply says, “Put
this view at this X coordinate and this Y coordinate.” Under the hood, these properties will modify
translationX or translationY to put the view where you want it to be. That means that a call to
mSunView.setY(50) really means this:


mSunView.setTranslationY(50 - mSunView.getTop())


Using different interpolators


Your animation, while pretty, is abrupt. If the sun was really sitting there perfectly still in the sky,
it would take a moment for it to accelerate into the animation you see. To add this sensation of
acceleration, all you need to do is use a TimeInterpolator. TimeInterpolator has one role: to change
the way your animation goes from point A to point B.


Add a line of code to startAnimation() to make your sun speed up a bit at the beginning using an
AccelerateInterpolator.


Listing 32.10  Adding acceleration (SunsetFragment.java)


private void startAnimation() {
float sunYStart = mSunView.getTop();
float sunYEnd = mSkyView.getHeight();


ObjectAnimator heightAnimator = ObjectAnimator
.ofFloat(mSunView, "y", sunYStart, sunYEnd)
.setDuration(3000);
heightAnimator.setInterpolator(new AccelerateInterpolator());


heightAnimator.start();
}


Run Sunset one more time and press to see your animation. Your sun should now start moving slowly
and accelerate to a quicker pace as it moves toward the horizon.


There are a lot of styles of motion you might want to use in your app, so there are a lot of different
TimeInterpolators. To see all the interpolators that ship with Android, look at the “Known Indirect
Subclasses” section in the reference documentation for TimeInterpolator.


Color evaluation


Now that your sun is animating down, let’s animate the sky to a sunset-y color. Inside of
onCreateView(...), pull all of the colors you defined in colors.xml into instance variables.

Free download pdf