Google

Sunday, July 11, 2010

View-based Animation



The main activity file (AnimationViewAnimation.java) :
 package com.ava;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class AnimationViewAnimation extends Activity {
ListView lv;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
setupListView();
this.setupButton();
}
private void setupListView()
{
String[] listItems = new String[]
{
"Item 1", "Item 2", "Item 3",
"Item 4", "Item 5", "Item 6",
};
ArrayAdapter listItemAdapter =
new ArrayAdapter(this
,android.R.layout.simple_list_item_1
,listItems);
lv = (ListView)this.findViewById(R.id.list_view_id);
lv.setAdapter(listItemAdapter);
}
private void setupButton()
{
Button b = (Button)this.findViewById(R.id.btn_animate);
b.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v)
{
animateListView();
}
});
}
private void animateListView()
{
ListView lv = (ListView)this.findViewById(R.id.list_view_id);
lv.startAnimation(new ViewAnimation(lv));
}
}

The animation class (ViewAnimation.java):

 package com.ava;
import android.app.Activity;
import android.opengl.Matrix;
import android.text.Layout;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import android.widget.ListView;
public class ViewAnimation extends Animation
{ ListView v;
public ViewAnimation(ListView _v){v = _v;}
@Override
public void initialize(int width, int height, int parentWidth,
int parentHeight)
{
super.initialize(width, height, parentWidth, parentHeight);
setDuration(2500);
setFillAfter(true);
setInterpolator(new LinearInterpolator());
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t)
{ float centerX = (float)v.getWidth()/2, centerY = (float)v.getHeight()/2;
final android.graphics.Matrix matrix = t.getMatrix();
matrix.setScale(interpolatedTime, interpolatedTime);
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}


The layout file (list_layout.xml):
 <?xml version="1.0" encoding="utf-8"?>
<!-- This file is at /res/layout/list_layout.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/btn_animate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Animation"
/>
<ListView
android:id="@+id/list_view_id"
android:persistentDrawingCache="animation|scrolling"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>



The java files put in src folder.
The layout xml file put in res/layout folder.