Background Color Transition Animation in Android
Last Updated :
06 Feb, 2022
In Android, animations can be applied to any UI element to make the application look more appealing. There are many pre-defined animations available to use in Android. However, custom animations can be created in XML format and applied to UI elements. Once such animation is color transition and in this article, we shall implement a color-changing transition to the background in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Button as shown below.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:id = "@+id/relative_layout_1"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< Button
android:id = "@+id/button_1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "start"
android:layout_centerInParent = "true" />
</ RelativeLayout >
|
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package org.geeksforgeeks.changingbackgroundanimation
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.TransitionDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.RelativeLayout
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mRelativeLayout = findViewById<RelativeLayout>(R.id.relative_layout_1)
val mButton = findViewById<Button>(R.id.button_1)
val mColors = arrayOf(ColorDrawable(Color.GREEN), ColorDrawable(Color.RED))
mButton.setOnClickListener {
val mTransition = TransitionDrawable(mColors)
mRelativeLayout.background = mTransition
mTransition.startTransition( 2000 )
}
}
}
|
Output:
You can see that the background color changes from green to red in 2 seconds.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...