Android学习(17)自定义动画_MyHeart(跳动的心)
程序员文章站
2024-03-24 10:59:04
...
Android学习(17)自定义动画_MyHeart(跳动的心)
1.在xml中配置动画——心变大和变小(scale)
(1)large.xml
<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:duration="500"
android:pivotX="50%"
android:pivotY="50%"
android:fromXScale="0.2"
android:toXScale="0.1"
android:fromYScale="0.2"
android:toYScale="0.1">
</scale>
(2)small.xml
<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:duration="500"
android:pivotX="50%"
android:pivotY="50%"
android:fromXScale="1"
android:toXScale="0.2"
android:fromYScale="1"
android:toYScale="0.2">
</scale>
2.在布局文件中加载图片
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.test.androidtest.MyHeart">
<ImageView
android:id="@+id/ivHeart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/heart"/>
</LinearLayout>
3.在Activity中开启动画
public class MyHeart extends AppCompatActivity implements Animation.AnimationListener{
private ImageView iv;
//定义两个动画对象:变大和变小
private Animation large,small;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myheart);
iv = (ImageView)findViewById(R.id.ivHeart);
//引入XML配置动画
large = AnimationUtils.loadAnimation(this,R.anim.large);
small = AnimationUtils.loadAnimation(this,R.anim.small);
//设置动画监听
large.setAnimationListener(this);
small.setAnimationListener(this);
//给ImageView绑定动画效果,并开始动画
iv.startAnimation(small);
}
//实现AnimationListener接口,并重写它的方法
@Override
public void onAnimationStart(Animation animation) {
}
//当动画结束时执行
@Override
public void onAnimationEnd(Animation animation) {
//判断当前的状态
//如果当前动画是变大效果
if (animation.hashCode() == large.hashCode()) {
//给ImageView绑定变小的动画,并执行
iv.startAnimation(small);
}else{
//否则给ImageView绑定变大的动画,并执行
iv.startAnimation(large);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
声明:
1.知识点来源于《网易云课堂》——《Android基础****》
2.本文只用于本人自身学习记录,如有侵权,请立即通知本人更改或删除