意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

Android属性动画(一):Animator属性动画相对于Animation的优势

来源:恒创科技 编辑:恒创科技编辑部
2022-08-19 13:59:16


  前面的博客​​ Android 动画效果(一): 四种动画基础(Alpha、Translate、Rotate、Scale) ​​​和​​ Android 动画效果(二):四种基础动画的 **动态设置、动画监听、组合动画 ​​​中已经介绍了普通的动画Animation,通过Animation已经可以实现不少动画效果,但是实际上Android还为我们提供了一种动画——Animatior(属性动画),为什么还要为我们再提供一种动画呢?我们来看下Animator相比Animation的优势在哪里。
  现在我们就来比较一下二者的区别。

Animation效果演示

1、布局
关于布局我就不多说了,大家都看的懂,只是这里我们给ImageView设置了一个点击事件也就是这句代码​​​android:onClick="imageclick"​


Android属性动画(一):Animator属性动画相对于Animation的优势

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"

<Button
android:id="@+id/btn_ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始移动"

<ImageView
android:id="@+id/imageview_ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="imageclick"
android:src="@drawable/hi"/>

</LinearLayout>

2、Animation动画
我们先使用animation动画。当点击Button时开始动画

public void onClick(View v) {
TranslateAnimation animation =new TranslateAnimation(0,300,0,300);
animation.setDuration(2000);
//记录动画的结束位置,停留在那里
animation.setFillAfter(true);
imageview.startAnimation(animation);
}
//ImageView的点击事件监听
public void imageclick(View view){
Toast.makeText(MainActivity_advatage.this, "当前图片被点击了", Toast.LENGTH_SHORT).show();
}

3、效果

Android  属性动画(一):Animator属性动画相对于Animation的优势_点击事件


通过图片展示可以看出动画完成后,当我点击动画时,动画的点击事件并未响应(没有弹出Toast),当我点击动画原来的位置时弹出了Toast,显然这并不合乎常理。

Animator效果演示

1、将动画进行修改为属性动画。

@Override
public void onClick(View v) {
// imageview.setTranslationX(translationX)
//像这种有set、get方法的属性才能被ObjectAnimator进行设置
ObjectAnimator.ofFloat(imageview,"translationX", 0,300).setDuration(2000).start();
ObjectAnimator.ofFloat(imageview,"translationY", 0,300).setDuration(2000).start();

2、效果展示

Android  属性动画(一):Animator属性动画相对于Animation的优势_点击事件_02


通过上面的效果图可以看出,这次,我们点击图片,图片的点击事件进行了响应,而点击图片的原来位置将没有反应。

二者区别

Animation只是对我们的界面进行了重新的绘制,并不能响应图片的属性,而Animator则可以进行属性的响应,在后面的博客中将对属性动画的使用进行进一步的讲解。


上一篇: 租用美国服务器:潜在的风险与应对策略。 下一篇: Android : GestureDetector手势检测