Search code examples
androidandroid-animationanimator

How to use animatorSet to change background color of a View


I am aiming at animating different things simultaneously. I have successfully used AnimatorSet to scale up my textView

val textViewAnimatorX = ObjectAnimator.ofFloat(txtView, View.SCALE_X, 0.8f, 1.2f)
val textViewAnimatorY = ObjectAnimator.ofFloat(txtView, View.SCALE_Y, 0.8f, 1.2f)

val animatorSet = AnimatorSet()
animatorSet.playTogether(textViewAnimatorX, textViewAnimatorY)
animatorSet.setDuration(500)
animatorSet.start()

How can i use animator set to simultaneously change the root view background color?


Solution

  • Assume this is your layout file.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/rootView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
    
    
        <TextView
            android:id="@+id/txtView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is text view" />
    
    </LinearLayout>
    

    Here is the code to simultaneously change the root view background color.

    val textViewAnimatorX = ObjectAnimator.ofFloat(txtView, View.SCALE_X, 0.8f, 1.2f)
    val textViewAnimatorY = ObjectAnimator.ofFloat(txtView, View.SCALE_Y, 0.8f, 1.2f)
    
    // Create a new ObjectAnimator instance to change background color of root view.
    val currentColor = rootView.solidColor
    val newColor = Color.GREEN
    val rootViewBackground = ObjectAnimator.ofObject(
        rootView,
        "backgroundColor",
        ArgbEvaluator(),
        currentColor,
        newColor
    )
    
    val animatorSet = AnimatorSet()
    // Simultaneously change the root view background color.
    animatorSet.playTogether(textViewAnimatorX, textViewAnimatorY, rootViewBackground)
    animatorSet.setDuration(500)
    animatorSet.start()