package com.test.tweenanimation;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import java.util.Timer;
import java.util.TimerTask;
/**
* 蝴蝶飞舞 用该案例来演示逐帧动画和补间动画
*/
public class ButterflyActivity extends AppCompatActivity {
private float curX = 0;
private float curY = 30;
float nextX = 0;
float nextY = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_butterfly);
final ImageView butterfly = (ImageView) findViewById(R.id.butterfly);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
if (nextX > 300) {
curX = nextX = 0;
} else {
nextX += 10;
}
nextY = curY+(float) (Math.random() * 20 - 5);
TranslateAnimation animation = new TranslateAnimation(curX, nextX, curY, nextY);
curX = nextX;
curY = nextY;
animation.setDuration(200);
butterfly.startAnimation(animation);
}
}
};
final AnimationDrawable anim = (AnimationDrawable) butterfly.getBackground();
butterfly.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
anim.start();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(0x123);
}
}, 0, 300);
}
});
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:background="#fff"
tools:context="com.test.tweenanimation.ButterflyActivity">
<ImageView
android:id="@+id/butterfly"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@anim/butterfly"
/>
</RelativeLayout>
动画资源文件
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/butterfly_f01" android:duration="120" />
<item android:drawable="@drawable/butterfly_f02" android:duration="120" />
<item android:drawable="@drawable/butterfly_f03" android:duration="120" />
<item android:drawable="@drawable/butterfly_f04" android:duration="120" />
<item android:drawable="@drawable/butterfly_f05" android:duration="120" />
<item android:drawable="@drawable/butterfly_f06" android:duration="120" />
</animation-list>