Sunday, February 22, 2015

Implement color animation with ValueAnimator

To implement color animation with ValueAnimator:


package com.example.valueanimatorofcolor;

import com.example.objectanimatorofargb.R;

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 = 0xFFffffff;
int colorStart = view.getSolidColor();
int colorEnd = 0xFF000000;

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

}

<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"
tools:context="com.example.valueanimatorofcolor.MainActivity" >

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android-coding.blogspot.com"
android:textSize="28dp"
android:textStyle="bold" />

<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>

No comments:

Post a Comment