一、概念
Android的补间动画与逐帧动画不一样的地方在于逐帧动画需要连续播放图片来模拟动画效果而补间动画则是通过定义开始和结束帧,中间通过简便的动画效果来实现。Android得到补间动画有四种:
- AlphaAnimation:透明渐变动画,对应<alpha>标签
- TranslateAnimation:平移动画,对应<translate>标签
- ScaleAnimation:缩放动画,对应<scale>标签
- RotateAnimation:旋转动画,对应<rotate>标签
二、代码实现补间动画
以透明渐变动画为例,在布局文件中添加一个按钮以及一个ImageView
然后在代码中定义按钮的点击事件如下
<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"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显示动画"
/>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/guoqing"
android:visibility="gone"
/>
</LinearLayout>
![](https://i-blog.csdnimg.cn/blog_migrate/3dea49501859e9b93793e14d699cece8.png)
然后在代码中定义按钮的点击事件如下
package com.example.animationdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(this);;
iv = (ImageView)findViewById(R.id.imageView);
}
@Override
public void onClick(View v) {
AlphaAnimation anim = new AlphaAnimation(0, 1.0f);
anim.setDuration(5000);
anim.setFillAfter(true);
iv.setVisibility(View.VISIBLE);
iv.startAnimation(anim);
}
}
三、xml布局实现补间动画
在资源文件目录下新建“anim”文件夹并添加anim_alpha.xml文件如下
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="0"
android:toAlpha="1.0"
android:fillAfter="true"
android:duration="5000"
>
</alpha>
然后在代码中找到此动画
iv.setVisibility(View.VISIBLE);
AlphaAnimation anim = (AlphaAnimation) AnimationUtils.loadAnimation(this, R.anim.anim_alpha);
iv.startAnimation(anim);
两种方法实现的效果是一样的
![](https://i-blog.csdnimg.cn/blog_migrate/26dc6302b4c47571c002b4c23fd0e237.gif)