转载:http://blog.csdn.net/yanzi1225627/article/details/47850471

最近又用到了动画,决定把几次项目里用到的动画走过的弯路总结一下,顺便梳理下android的动画体系。众所周知,android动画分三类:一是View 动画,又叫Tween动画,二是frame 动画(帧动画),又叫drawable 动画,三是属性动画,即property animation.

转载地址:http://blog.csdn.net/yanzi1225627/article/details/47850471

View动画,根据作用又分为缩放动画ScaleAnimation/移位动画TranslateAnimation / 透明度动画AlphaAnimation / 旋转动画RotateAnimation,这四个动画都继承android.view.animation下的Animation类。继承Animation的除了这四个类外,还有AnimationSet,关系图如下所示:

帧动画 对应AnimationDrawable类,继承自DrawableContainer,通过加载多个Drawable来一帧一帧播放达到动画效果。尽管很多人觉得这个不值一提,但是某些动画效果,如显示个小羊吃草还必须得用这个动画。 
       接下来进入正题谈属性动画,该动画从android3.0引入,API11引入,是为了弥补view动画的不足。正式项目里用的话为了兼容android2.3可以用NineOldAndroids,直接将生成的jar包放进去就ok了。 
       属性动画都在android.animation包下,基类是Animator类,子类为ValueAnimator和AnimatorSet(作用同view动画的AnimationSet相同),ValueAnimator的子类有ObjectAnimator和TimeAnimator,一般我们用属性动画ObjectAnimator就ok了。不妨简单对比下和view动画架构上的异同: 
       View动画,包名android.view.animation,基类为Animation,核心子类为TranslateAnimation,ScaleAnimation,AlphaAnimation,RotateAnimation及AnimationSet。 
       Property动画,包名android.animation,基类为Animator,核心子类为AnimatorSet,ValueAnimator,ObjectAnimator,TimeAnimator。 
       在详细对比属性动画和view动画前,先介绍个函数setTranslationX和setTranslationY,api版本为11,是设置view相对原始位置的偏移量,正式项目用的话考虑到兼容api11之前的用nineoldandroids里的ViewHelper即可。

public void setTranslationX (float translationX)Added in API level 11
Sets the horizontal location of this view relative to its left position. This effectively positions the object post-layout, in addition to wherever the object's layout placed it.Related XML Attributes
android:translationX
Parameters
translationX    The horizontal position of this view relative to its left position, in pixels.

上面是api介绍,即相对left position的偏移,所谓left position也即getLeft(),同时可以在xml里直接用android:translationX进行设置。关于view的位置,我们最常用的莫过于android:layoutMargin这一套,用来设置相对父布局的偏移,在java代码里可以通过新建或更新view的LayoutParams进行修改,如下所示:

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)text.getLayoutParams();params.leftMargin = 0;params.rightMargin = 0;params.setMargins(0, 0, 0, 0);text.setLayoutParams(params);

之所以说有时需要新建Params而有时候需要更新,是因为有时候从view取来的params是空的,这个日后开篇文章专门谈这个问题。总之,通过view的LayoutParams设置margin最终影响了view的位置,这个同时会改变view的getLeft/getRight等变量。但通过setTranslationX改变view的位置,是不改变view的LayoutParams的,也即不改变getLeft等view的信息。 但他确实改变了view的位置,这一点可以通过获取其在window或screen的坐标,或通过getLocationInWindow及如下所示的api等到view的精确位置:

text.getLocationInWindow(pos);text.getLocationOnScreen(pos);text.getLocalVisibleRect()text.getGlobalVisibleRect()

总结: 
1,setTranslationX改变了view的位置,但没有改变view的LayoutParams里的margin属性; 
2,它改变的是android:translationX 属性,也即这个参数级别是和margin平行的。

下面来看这个例子,通过点击按键让一个view从最左边移动到屏幕的最右边,分别用view的TranslateAnimation和属性动画来实现。 
布局代码:

<RelativeLayout 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"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="50dp"android:background="@android:color/holo_green_light"android:orientation="vertical"><TextViewandroid:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world" /></LinearLayout><Buttonandroid:id="@+id/btn_start_anim"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="属性动画" /><Buttonandroid:id="@+id/btn_start_anim2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_toLeftOf="@id/btn_start_anim"android:layout_centerVertical="true"android:layout_marginRight="40dp"android:text="复位" /><Buttonandroid:id="@+id/btn_reset_pos"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_toRightOf="@id/btn_start_anim"android:layout_centerVertical="true"android:layout_marginLeft="40dp"android:text="复位" /></RelativeLayout>

Java代码: 
MainActivity.java

package com.example.yanzi.myapplication;import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;
import com.yanzi.util.UiUtil;public class MainActivity extends ActionBarActivity implements View.OnClickListener{private static final String TAG = "YanZi";Button btn_start_anim;Button btn_reset_pos;Button btn_start_anim2;TextView text;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initData();initUI();}private void initData(){UiUtil.initialize(getApplicationContext());}private void initUI(){btn_start_anim = (Button)findViewById(R.id.btn_start_anim);btn_start_anim.setOnClickListener(this);btn_start_anim2 = (Button)findViewById(R.id.btn_start_anim2);btn_start_anim2.setOnClickListener(this);btn_reset_pos = (Button)findViewById(R.id.btn_reset_pos);btn_reset_pos.setOnClickListener(this);text = (TextView)findViewById(R.id.text);text.setOnClickListener(this);LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)text.getLayoutParams();params.leftMargin = 0;params.rightMargin = 0;params.setMargins(0, 0, 0, 0);text.setLayoutParams(params);}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.btn_start_anim:playAnim1();break;case R.id.btn_start_anim2:playAnim2();break;case R.id.btn_reset_pos:resetPos();break;case R.id.text:printParams();break;default:break;}}public void printParams(){LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)text.getLayoutParams();if(params != null){String s =  "leftMargin = " + params.leftMargin + " rightMargin = " + params.rightMargin+ " getLeft = " + text.getLeft() + " getRight = " + text.getRight() + " getWidth = " + text.getWidth();Log.i(TAG, s);int[] pos = new int[2];text.getLocationInWindow(pos);Log.i(TAG, "location, x = " + pos[0] + " y = " + pos[1]);Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();}}private void playAnim1(){int w = text.getWidth();int screenW = UiUtil.getScreenWidth();int transX = screenW - w;ObjectAnimator transAnim = ObjectAnimator.ofFloat(text, "translationX", 0, transX);transAnim.addListener(new Animator.AnimatorListener() {@Overridepublic void onAnimationStart(Animator animator) {}@Overridepublic void onAnimationEnd(Animator animator) {}@Overridepublic void onAnimationCancel(Animator animator) {}@Overridepublic void onAnimationRepeat(Animator animator) {}});transAnim.setDuration(300);transAnim.start();;}private void playAnim2(){int w = text.getWidth();int screenW = UiUtil.getScreenWidth();int transX = screenW - w;TranslateAnimation transAnim = new TranslateAnimation(0, transX, 0, 0);transAnim.setDuration(300);text.setAnimation(transAnim);transAnim.start();}private void resetPos(){ViewHelper.setTranslationX(text, 0);}
}

用到了一个辅助类获得屏幕的宽高和dip转px:

package com.yanzi.util;import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ListAdapter;
import android.widget.ListView;public class UiUtil {private static final String TAG =  "YanZi_UiUtil";private static int screenWidth = 0;private static int screenHeight = 0;private static float screenDensity = 0;private static int densityDpi = 0;private static int statusBarHeight = 0;public static void initialize(Context context){if (context == null)return;DisplayMetrics metrics = new DisplayMetrics();WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);wm.getDefaultDisplay().getMetrics(metrics);screenWidth = metrics.widthPixels;     // 屏幕宽度screenHeight = metrics.heightPixels;   // 屏幕高度screenDensity = metrics.density;      // 0.75 / 1.0 / 1.5 / 2.0 / 3.0densityDpi = metrics.densityDpi;  //120 160 240 320 480Log.i(TAG, "screenDensity = " + screenDensity + " densityDpi = " + densityDpi);}public static int dip2px(float dipValue){return (int)(dipValue * screenDensity + 0.5f);}public static int px2dip(float pxValue){return (int)(pxValue / screenDensity + 0.5f);}public static int getScreenWidth() {return screenWidth;}public static int getScreenHeight() {return screenHeight;}}

大概说下里面核心的几个函数: 
1,使用view动画TranslateAnimation:

private void playAnim2(){int w = text.getWidth();int screenW = UiUtil.getScreenWidth();int transX = screenW - w;TranslateAnimation transAnim = new TranslateAnimation(0, transX, 0, 0);transAnim.setDuration(300);text.startAnimation(transAnim);}

2,使用属性动画移位:

private void playAnim1(){int w = text.getWidth();int screenW = UiUtil.getScreenWidth();int transX = screenW - w;ObjectAnimator transAnim = ObjectAnimator.ofFloat(text, "translationX", 0, transX);transAnim.addListener(new Animator.AnimatorListener() {@Overridepublic void onAnimationStart(Animator animator) {}@Overridepublic void onAnimationEnd(Animator animator) {}@Overridepublic void onAnimationCancel(Animator animator) {}@Overridepublic void onAnimationRepeat(Animator animator) {}});transAnim.setDuration(300);transAnim.start();;}

3,点击text打印它的坐标:

 public void printParams(){LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)text.getLayoutParams();if(params != null){String s =  "leftMargin = " + params.leftMargin + " rightMargin = " + params.rightMargin+ " getLeft = " + text.getLeft() + " getRight = " + text.getRight() + " getWidth = " + text.getWidth();Log.i(TAG, s);int[] pos = new int[2];text.getLocationInWindow(pos);Log.i(TAG, "location, x = " + pos[0] + " y = " + pos[1]);Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();}}

4,使用属性动画后如果想复位:

private void resetPos(){ViewHelper.setTranslationX(text, 0);}

直接将translationX设为0即可,而不是上次偏移量的相反数。正因为如此,重复点击属性动画,看到view每次都从最左边到最右边,并最终停在最右边。因为属性动画的执行过程就是setTranslationX(0), 1, 2, 3, 4,……..N的过程,所以才会有看到的效果。

另外,可以看到使用view的TranslateAnimation动画播放完毕后,view瞬间又回到了原点;而使用属性动画移位后view位置确实发生了改变。但LayoutParams里的margin和getLeft信息并未改变。有没有办法让view的TranslateAnimation播放完毕后,停在那个地方呢?

肯定是有,加上这句话:transAnim.setFillAfter(true);之后运行发现view确实停在了屏幕的右侧,但是点击右侧的textview并没有触发打印参数的函数,而点击textview的初始位置才触发。所以它并没有改变view的位置,仅仅是绘制在了屏幕的右侧。因此,如果使用view动画但又想真正改变view位置需要如下代码:

private void playAnim2(){int w = text.getWidth();int screenW = UiUtil.getScreenWidth();int transX = screenW - w;TranslateAnimation transAnim = new TranslateAnimation(0, transX, 0, 0);transAnim.setDuration(300);
//        transAnim.setFillAfter(true);transAnim.setAnimationListener(new Animation.AnimationListener() {@Overridepublic void onAnimationStart(Animation animation) {}@Overridepublic void onAnimationEnd(Animation animation) {updateParams();}@Overridepublic void onAnimationRepeat(Animation animation) {}});text.startAnimation(transAnim);}private void updateParams(){int w = text.getWidth();int screenW = UiUtil.getScreenWidth();LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) text.getLayoutParams();params.leftMargin = screenW - w;text.setLayoutParams(params);}

即使用LayoutParams在动画结束后设置下就ok了,这样也能达到属性动画改变view的位置的效果。view 动画+updateParams 约等于property动画效果。 
       但是切忌,使用view动画+updateParams策略时,务必注意不要使用transAnim.setFillAfter(true);这句话,先看看setFillAfter的api:

If fillAfter is true, the transformation that this animation performed will persist when it is finished. Defaults to false if not set. Note that this applies to individual animations and when using an AnimationSet to chain animations.Related XML Attributes
android:fillAfter
Parameters
fillAfter   true if the animation should apply its transformation after it ends

如果为true,动画结束后关于view的变换会一直存在。在view动画+updateParams+transAnim.setFillAfter(true)这种策略下,view最终的绘制位置等于将view先updateParams后在新的位置基础上,再进行动画移位,一般情况下这并不是我们想要的! 
       基本上可以这么说,如果需要view位置真正改变setFillAfter一定不要设! 
       时间原因,很多东西只有下次再写了,关于属性动画和view动画详细对比可以参考官方文档里How Property Animation Differs from View Animation这一段,见后文。

总之,要知其然并知其所以然,不要一味否定view动画而肯定属性动画。很多多个界面间的复杂效果非view动画不可,用属性动画只能掉坑里,我是两种坑都掉过。如果想改变动画后view的属性,如位置,可以用属性动画也可以用view动画+updateParams,当然前者更省事。在有些情况下,仅仅是想得到动画的呈现,动画结束后的位置就是view的初始位置,如view从一个地方飞过来,动画结束时view的位置就是view的位置时,此时view动画最合适!

he view animation system provides the capability to only animate View objects, so if you wanted to animate non-View objects, you have to implement your own code to do so. The view animation system is also constrained in the fact that it only exposes a few aspects of a View object to animate, such as the scaling and rotation of a View but not the background color, for instance.Another disadvantage of the view animation system is that it only modified where the View was drawn, and not the actual View itself. For instance, if you animated a button to move across the screen, the button draws correctly, but the actual location where you can click the button does not change, so you have to implement your own logic to handle this.With the property animation system, these constraints are completely removed, and you can animate any property of any object (Views and non-Views) and the object itself is actually modified. The property animation system is also more robust in the way it carries out animation. At a high level, you assign animators to the properties that you want to animate, such as color, position, or size and can define aspects of the animation such as interpolation and synchronization of multiple animators.The view animation system, however, takes less time to setup and requires less code to write. If view animation accomplishes everything that you need to do, or if your existing code already works the way you want, there is no need to use the property animation system. It also might make sense to use both animation systems for different situations if the use case arises.

文中测试代码下载: http://download.csdn.net/detail/yanzi1225627/9034125  
--—–--本文系原创,转载注明作者yanzi1225627

Android之动画精讲一:从setTranslationX谈属性动画和view动画的区别相关推荐

  1. Android——Fragment实例精讲——底部导航栏+ViewPager滑动切换页面

    说明: 实现效果: 1- 用ViewPager实现Fragmen之间的切换 2- 底部用RadioGroup实现,更方便的实现图片和字体颜色的改变,更方便的通过RadioButton的点击事件来控制页 ...

  2. 精讲▍自然语言处理浅谈 技术/工具/方法和应用全都有了

    NLP方向 作者|陈颂光  编辑|树袋熊 由于人们之间普遍以自然语言的形式交流,互联网和各种数据库中的这些非结构化数据中蕴藏了价值连城的大量信息.然而,对于计算机而言,理解自然语言相当困难,实际上这可 ...

  3. Python精讲Numpy基础,大牛笔记详细解释

    https://www.toutiao.com/a6664936105076326920/ 总认为Numpy是渣渣,直到深入接触以后才知道功能这么强大.堪比Matlab啊.果然是人生苦短,我用Pyth ...

  4. matlab imcrop 对应python函数_Python精讲Numpy基础,大牛笔记详细解释

    总认为Numpy是渣渣,直到深入接触以后才知道功能这么强大.堪比Matlab啊.果然是人生苦短,我用Python.所以本文作为一个记录&笔记,文章内容大多数取自网络以&官网快速入门等, ...

  5. pythonnumpy详解_Python精讲Numpy基础,大牛笔记详细解释

    以前总认为Numpy是渣渣,直到深入接触以后才知道功能这么强大.堪比Matlab啊.果然是人生苦短,我用Python.所以本文作为一个记录&笔记,文章内容大多数取自网络以&官网快速入门 ...

  6. 高薪程序员Java面试题精讲系列汇总

    因CSDN没有分类归纳博客的功能,所以特写本帖汇总<高薪程序员面试题精讲系列>教程,方便大家查阅!希望各位小伙伴可以从我的拙作中掌握Java的高频面试题,也希望各位可以多给予指教!目前本系 ...

  7. 精讲精练_参悟Android核心技术-张晓飞-专题视频课程

    精讲精练_参悟Android核心技术-92074人已学习 课程介绍         如果你没有Android基础, 它是你的首选:从搭建环境开始,逐步讲解四大组件.用户界面.数据存储等核心知识: 如果 ...

  8. Android之动画全讲-刘志远-专题视频课程

    Android之动画全讲-7291人已学习 课程介绍         本课程讲解了Android中的帧动画,补间动画,属性动画的动画实现过程 课程收益     让学员掌握Android中基本的动画形式 ...

  9. Android初级开发第九讲--动画

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! Android中动画的应用,在应用管理软件.购物软件.追星软件等比较广泛:比如常见的进度条设计,此处 ...

最新文章

  1. [转]XPS转JPG转换器
  2. Pacemaker+Corosync PostgreSQL流复制HA的部署(pha4pgsql)
  3. 关键字提取_从杂乱无章的表格中找出关键字,批量提取字符
  4. 转:如何在 LoadRunner 脚本中做关联 (Correlation)
  5. 配置hosts快速访问GitHub
  6. 解决Appium连接报错Could not find ‘apksigner.jar‘
  7. oracle numlist,oracle sql str2numlist numtabletype
  8. maven打包报错找不到符号,由于找不到类中方法的解决思路
  9. js里面把密码encode_PHP会员找回密码功能的简单实现
  10. /etc/group
  11. 吴昂雄回应Arm中国控制权争夺:Arm罢免我无效
  12. Loadrunner教程
  13. 基于微信小程序会议室预约系统设计与实现毕业设计毕设开题报告参考
  14. 双基因突变患者_肺癌多EGFR基因突变 7成脑转移 双标靶并用 有效控制肿瘤
  15. ArcGIS中shp文件的裁剪
  16. 解决This is probably not a problem with npm. There is likely additional logging output above.的问题
  17. 计算机在地理科学中的作用,中学地理教学中工具的重要性—胡阳新推荐
  18. SPSS 自动线性建模 模型导出方法
  19. 基于 Eclipse+Java Swing + Mysql 学生选课管理系统
  20. Windows 与 Linux之间进行文件传输,文件传输工具Cuteftp的使用方法。

热门文章

  1. 实际体验SpanT 的惊人表现
  2. 如何在 .NET 程序万种死法中有效的生成 Dump (上)
  3. JWT 介绍 - Step by Step
  4. 三种方式让你轻松监控 EntityFramework 中的 sql 流转
  5. Orleans 知多少 | Orleans 中文文档上线
  6. 副业刚需? 恐怕并不靠谱!
  7. 聊聊统一身份认证服务
  8. 《ASP.NET Core 微服务实战》-- 读书笔记(第5章)
  9. K8S水平伸缩器 - 自动伸缩微服务实例数量
  10. UnitTest in .NET(Part 4)