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

(gtxtreme123) #1
Color evaluation

Listing 32.11  Pulling out sunset colors (SunsetFragment.java)


public class SunsetFragment extends Fragment {
...
private View mSkyView;


private int mBlueSkyColor;
private int mSunsetSkyColor;
private int mNightSkyColor;
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
mSkyView = view.findViewById(R.id.sky);


Resources resources = getResources();
mBlueSkyColor = resources.getColor(R.color.blue_sky);
mSunsetSkyColor = resources.getColor(R.color.sunset_sky);
mNightSkyColor = resources.getColor(R.color.night_sky);


mSceneView.setOnClickListener(new View.OnClickListener() {
...
});


return view;
}


Now add an additional animation to startAnimation() to animate the sky from mBlueSkyColor to
mSunsetSkyColor.


Listing 32.12  Animating sky colors (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());


ObjectAnimator sunsetSkyAnimator = ObjectAnimator
.ofInt(mSkyView, "backgroundColor", mBlueSkyColor, mSunsetSkyColor)
.setDuration(3000);


heightAnimator.start();
sunsetSkyAnimator.start();
}


This seems like it is headed in the right direction, but if you run it you will see that something is amiss.
Instead of moving smoothly from blue to orange, the colors will kaleidoscope wildly.


The reason this happens is that a color integer is not a simple number. It is four smaller numbers
schlupped together into one int. So for ObjectAnimator to properly evaluate which color is halfway
between blue and orange, it needs to know how that works.


When ObjectAnimator’s normal understanding of how to find values between the start and end is
insufficient, you can provide a subclass of TypeEvaluator to fix things. A TypeEvaluator is an object

Free download pdf