Simple Property Animation
The getTop() method is one of four methods on View that return the local layout rect for that view:
getTop(), getBottom(), getRight(), and getLeft(). A view’s local layout rect is the position and
size of that view in relation to its parent, as determined when the view was laid out. It is possible to
change the location of the view onscreen by modifying these values, but it is not recommended. They
are reset every time a layout pass occurs, so they tend not to hold their value.
In any event, the animation will start with the top of the view at its current location. It needs to end
with the top at the bottom of mSunView’s parent, mSkyView. To get it there, it should be as far down as
mSkyView is tall, which you find by calling getHeight(). The getHeight() method returns the same
thing as getBottom() - getTop().
Now that you know where the animation should start and end, create and run an ObjectAnimator to
perform it.
Listing 32.8 Creating a sun animator (SunsetFragment.java)
private void startAnimation() {
float sunYStart = mSunView.getTop();
float sunYEnd = mSkyView.getHeight();
ObjectAnimator heightAnimator = ObjectAnimator
.ofFloat(mSunView, "y", sunYStart, sunYEnd)
.setDuration(3000);
heightAnimator.start();
}
Then hook up startAnimation() so that it is called every time the user presses anywhere in the scene.
Listing 32.9 Starting animation on press (SunsetFragment.java)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sunset, container, false);
mSceneView = view;
mSunView = view.findViewById(R.id.sun);
mSkyView = view.findViewById(R.id.sky);
mSceneView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startAnimation();
}
});
return view;
}
Run Sunset and press anywhere on the scene to run the animation (Figure 32.2).