首先在activity_tween布局文件里面写了一个ImageView和一个Button,分别都加上id,为了添加点击事件。这个点击事件在下面会说到,请注意哦!
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageTween"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<Button
android:id="@+id/tweenStartBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点 击"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="100dp" />
</RelativeLayout>
接下来我们在TweenActivity里面来写个简单的动画,在x轴水平方向移动
package com.fshsoft.AnimatorDemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* 补间动画
*/
public class TweenActivity extends Activity implements View.OnClickListener {
private ImageView imageTween;
private Button tweenStartBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tween);
imageTween = (ImageView) findViewById(R.id.imageTween);
tweenStartBtn = (Button) findViewById(R.id.tweenStartBtn);
imageTween.setOnClickListener(this);
tweenStartBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imageTween:
Toast.makeText(this,"图片点击事件",Toast.LENGTH_SHORT).show();
break;
case R.id.tweenStartBtn:
TranslateAnimation animation = new TranslateAnimation(0,400,0,0);//创建动画对象
animation.setDuration(1000);//显示时长
animation.setFillAfter(true);//动画停留在移动后的位置
imageTween.startAnimation(animation);
animation.start();//启动动画
break;
default:
break;
}
}
}
上面的图片动画我们已经看到了,当图片移动之后的位置,我们点击的时候不显示Toast,但是我们点击图片原来的位置,就可以弹出Toast,这个就是补间动画的缺陷,补间动画主要是为了显示,却做不到交互,所以Android3.0提出了属性动画的这个概念,很好的解决了这个问题。
属性动画(property animation)