1.在res文件夹中创建一个名为anim 的文件,并在里面创建类型为animator的xml文件配置动画

2.在anim_alpha.xml里配置动画的一些参数

(fromAlpha:起始的透明度 toAlpha:动画完成时的透明度)
3.在布局文件中添加ImageView来显示动画
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/anim_alpha"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/devil"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
4.在MainActivity.java中控制动画的开始
package swu.w1nfred.tweenanimationtest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
Animation alphaAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_alpha);
ImageView iv = findViewById(R.id.anim_alpha);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(3);
alphaAnimation.setFillAfter(true);
iv.startAnimation(alphaAnimation);
}
return true;
}
}
(setDuration()方法设置一次动画的持续时间,setRepeatCount()方法设置动画重复的次数,setFillAfter()方法设置动画是否保持变化后的状态)
动画效果:

补间动画.gif