ValueAnimator changes the background color… here is a solution to the problem.
ValueAnimator changes the background color
I want to create a screen where the background color constantly changes from red to blue. For some reason, it always crashes when I try to instantiate ValueAnimator. I don’t know what’s wrong with my code
Thanks
Animation classes
public BackgroundAnimation(Context context){
super(context);
ValueAnimator colorAnim = ObjectAnimator.ofInt(R.anim.animator, "backgroundColor", Color.RED, Color.BLUE);
colorAnim.setDuration(3000);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();
}
animator.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:propertyName="backgroundColor"/>
</set>
Main class
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.menu);
LinearLayout container = (LinearLayout) findViewById(R.id.container);
container.addView(new BackgroundAnimation(this));
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/TextView01"
android:gravity="center"
android:textSize="20sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/TextView02"
android:gravity="center"
android:textSize="20sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/ImageView01"
android:layout_width="fill_parent"
android:layout_height="300sp"/>
</LinearLayout>
Solution
You can use ObjectAnimator to change the background color:
For API >= 21
:
ObjectAnimator colorAnimator = ObjectAnimator.ofArgb(travelersListView.getBackground().mutate(), "tint", mCurrentBackground, mFadeColor);
colorAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
colorAnimator.start();
For backward support for API 16, use:
ObjectAnimator colorAnimator = ObjectAnimator.ofObject(travelersListView.getBackground().mutate(), "tint", new ArgbEvaluator(), mCurrentBackground, mFadeColor);
colorAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
colorAnimator.start();