Background ColorAnimator

ColorAnimator will change the background color of your view on button click. To implement color animation with ValueAnimator you will need to create valueanimator’s object and set animation properties to start the animation.

Today in this example I will show you how you can change background color of an image view on a button click without effecting image view. Follow the steps below to get this working:

Step1: Create a new android project in your android environment.

Step2: Copy and paste an image which will be displayed on app launch in your drawable folder. I have taken ic_launcher in this sample. You can change it to any of your choice.

Step3: Write below java code in your main activity:

 

package com.example.customimageview;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView title;
Button btnStart;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = (TextView) findViewById(R.id.title);
image = (ImageView) findViewById(R.id.image);
btnStart = (Button) findViewById(R.id.start);

btnStart.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
startColorAnimation(image);
}});
}

private void startColorAnimation(View view){
int colorStart = view.getSolidColor();
int colorEnd = 0xFFFF0000;

ValueAnimator colorAnim = ObjectAnimator.ofInt(
view, "backgroundColor", colorStart, colorEnd);
colorAnim.setDuration(2000);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(1);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();
}

}

 

Step4: Write below code in your layout file:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Animation" />

<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/ic_launcher" />

</LinearLayout>

 

Step5: Run to check the output as below:

coloanimator1

  • coloanimator2

Check my previous post I have published on Reveal Animations in Android 5.0

Leave a Comment: