Android Animation的使用记录

来源:互联网 发布:安卓登录源码 编辑:程序博客网 时间:2024/05/30 23:01

View Animation

ViewAnimation 也称为 Tween animation,主要包含alpha, scale, translate, rotate;可以直接通过xml申明动画,放在“res/anim/”下面。

alpha、scale、translate、rotator的xml设置参数

<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"    android:interpolator="@[package:]anim/interpolator_resource"    android:shareInterpolator=["true" | "false"] >    <!--alpha Float. 0.0代表全透明;1.0代表不透明-->    <alpha        android:fromAlpha="float"        android:toAlpha="float" />    <!--scale float. 1.0代表不拉伸-->    <scale        android:fromXScale="float"        android:toXScale="float"        android:fromYScale="float"        android:toYScale="float"        android:pivotX="float"        android:pivotY="float" />    <translate        android:fromXDelta="float"        android:toXDelta="float"        android:fromYDelta="float"        android:toYDelta="float" />    <rotate        android:fromDegrees="float"        android:toDegrees="float"        android:pivotX="float"        android:pivotY="float" />    <set>        ...    </set></set>

更详细的参数设置可以参考:View Animation Resource ; 使用指南可以到more detailed tutorial

Android动画有几个不懂的参数:FillEnabled、FillBefore、FillAfter

/*** Indicates whether the animation transformation should be applied before the* animation starts. The value of this variable is only relevant if mFillEnabled is true;* otherwise it is assumed to be true.*/boolean mFillBefore = true;/*** Indicates whether the animation transformation should be applied after the* animation ends.*/boolean mFillAfter = false;/*** Indicates whether fillBefore should be taken into account.*/boolean mFillEnabled = false;  

Interpolators,动画插值器

Class/Interface Description AccelerateDecelerateInterpolator An interpolator whose rate of change starts and ends slowly but accelerates through the middle. AccelerateInterpolator An interpolator whose rate of change starts out slowly and then accelerates. AnticipateInterpolator An interpolator whose change starts backward then flings forward. AnticipateOvershootInterpolator An interpolator whose change starts backward, flings forward and overshoots the target value, then finally goes back to the final value. BounceInterpolator An interpolator whose change bounces at the end. CycleInterpolator An interpolator whose animation repeats for a specified number of cycles. DecelerateInterpolator An interpolator whose rate of change starts out quickly and and then decelerates. LinearInterpolator An interpolator whose rate of change is constant. OvershootInterpolator An interpolator whose change flings forward and overshoots the last value then comes back. TimeInterpolator An interface that allows you to implement your own interpolator.

canvas相关的几个方法

canvas.save(); // 保存当前的画布canvas.translate(shapeHolder.getX(), shapeHolder.getY()); // 把canvas的原点在原来的基础上偏移x,yshapeHolder.getShape().draw(canvas); canvas.restore(); // 恢复画布

Property Animation

Property Animation 主要三个总要的类:ValueAnimator、ObjectAnimator、AnimatorSet。

Property Animation 和 View Animation的区别

  1. View Animation只能作用于View对象,并且只适用于一部分特性。而Property Animation可以作用于非View对象。
  2. View Animation只会修改View draw的地方,并不会修改实际的View本身。Property Animation可以给View的任意属性加上动画,并且修改View 本身。

Animation Listeners

  • Animator.AnimatorListener

    • onAnimationStart() - 动画开始时调用。
    • onAnimationEnd() - 动画结束时调用。
    • onAnimationRepeat() - 动画重复时调用。
    • onAnimationCancel() - 动画取消时调用。一个取消的动画仍然会调用 onAnimationEnd(), 不管如何结束。
  • AnimatorListenerAdapter,这个类实现Animator.AnimatorListener中的每个方法,不过什么都没做。我们可以继承它然后重写自己需要使用的回调。

  • ValueAnimator.AnimatorUpdateListener
    • onAnimationUpdate() - 每一帧做动画的时候调用。可以通过这个接口传递过来的ValueAnimator调用getAnimatedValue() 方法查询当前计算出来的值。使用ValueAnimator的时候需要继承它。

Animating Layout Changes to ViewGroups(LayoutTransition)

我们可以通过LayoutTransition给ViewGroup内部变化加上过渡动画,比如子View显示、消失以及内部的其他子View的移动变化动画。
LayoutTransition中总结了四种动画情况,我们可以通过setAnimator()传递自定义的一个Animator来实现不同的动画效果:

  • APPEARING - A flag indicating the animation that runs on items that are appearing in the container.
  • CHANGE_APPEARING - A flag indicating the animation that runs on items that are changing due to a new item appearing in the container.
  • DISAPPEARING - A flag indicating the animation that runs on items that are disappearing from the container.
  • CHANGE_DISAPPEARING - A flag indicating the animation that runs on items that are changing due to an item disappearing from the container.

可以通过设置XML属性android:animateLayoutChanges=”true”,会使用默认的LayoutTransition:

    <GridLayout        android:columnCount="4"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/gridContainer"        android:animateLayoutChanges="true"        />

通过代码,自定义LayoutTransition:

mTransition.setAnimator(LayoutTransition.CHANGE_APPEARING, changeIn);        mTransition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, changeOut);

Specifying Keyframes

Keyframe是 time/value (时间/值)对,定义在某个时间点应该取什么值。Keyframe都是结合PropertyValuesHolder来使用,至少官方API Demo里面是这样的。

Keyframe kf0 = Keyframe.ofFloat(0f, 0f);Keyframe kf1 = Keyframe.ofFloat(.5f, 360f);Keyframe kf2 = Keyframe.ofFloat(1f, 0f);PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2);ObjectAnimator rotationAnim = ObjectAnimator.ofPropertyValuesHolder(target, pvhRotation)rotationAnim.setDuration(5000ms);

Animating with ViewPropertyAnimator

Multiple ObjectAnimator objects:

ObjectAnimator animX = ObjectAnimator.ofFloat(myView, "x", 50f);ObjectAnimator animY = ObjectAnimator.ofFloat(myView, "y", 100f);AnimatorSet animSetXY = new AnimatorSet();animSetXY.playTogether(animX, animY);animSetXY.start();

One ObjectAnimator:

PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", 50f);PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 100f);ObjectAnimator.ofPropertyValuesHolder(myView, pvhX, pvyY).start();

ViewPropertyAnimator:

myView.animate().x(50f).y(100f);

在XML中申明animator

Property Animation的xml文件放置在res/animator目录中。
普通ValueAnimator的XML申明:

<animator xmlns:android="http://schemas.android.com/apk/res/android"    android:duration="1000"    android:valueFrom="1"    android:valueTo="0"    android:valueType="floatType"    android:repeatCount="1"    android:repeatMode="reverse"/>

ValueAnimator结合PropertyValuesHolder和Keyframe:

<animator xmlns:android="http://schemas.android.com/apk/res/android"          android:duration="1000"          android:repeatCount="1"          android:repeatMode="reverse">    <propertyValuesHolder>        <keyframe android:fraction="0" android:value="1"/>        <keyframe android:fraction=".2" android:value=".4"/>        <keyframe android:fraction="1" android:value="0"/>    </propertyValuesHolder></animator>

普通ObjectAnimator的XML申明:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"    android:duration="1000"    android:valueTo="200"    android:valueType="floatType"    android:propertyName="y"    android:repeatCount="1"    android:repeatMode="reverse"/>

ObjectAnimator结合PropertyValuesHolder和Keyframe申明:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"                android:duration="1000"                android:repeatCount="1"                android:repeatMode="reverse">    <propertyValuesHolder android:propertyName="x" android:valueTo="400"/>    <propertyValuesHolder android:propertyName="y" >    <keyframe android:fraction="0" android:value="800" />    <keyframe android:fraction=".2"android:interpolator="@android:anim/accelerate_interpolator" android:value="300"/>    <keyframe android:fraction="1"android:interpolator="@android:anim/accelerate_interpolator" android:value="1000" /></propertyValuesHolder></objectAnimator>

Drawable Animation

Drawable Animation 是以逐帧的方式播放一连串的Drawable resources;对应的类为AnimationDrawable。
在XML中申明:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"    android:oneshot="true">    <item android:drawable="@drawable/rocket_thrust1" android:duration="200" />    <item android:drawable="@drawable/rocket_thrust2" android:duration="200" />    <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /></animation-list>

在ImageView中使用animation-list:

AnimationDrawable rocketAnimation;public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);  rocketImage.setBackgroundResource(R.drawable.rocket_thrust);  rocketAnimation = (AnimationDrawable) rocketImage.getBackground();}public boolean onTouchEvent(MotionEvent event) {  if (event.getAction() == MotionEvent.ACTION_DOWN) {    rocketAnimation.start();    return true;  }  return super.onTouchEvent(event);}

注意点:

It’s important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged() method in your Activity, which will get called when Android brings your window into focus.

Layout Animation

Layout Animation主要是给Layout或者Group的子View加上动画。每一个子View都有相同的动画但是可以从不同的时间开始执行。

layoutAnimation标签和 LayoutAnimationController

LayoutAnimation的标签实现 – layoutAnimation

<?xml version="1.0" encoding="utf-8"?><layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"                 android:delay="1"                 android:animationOrder="normal"                 android:animation="@anim/slide_in_left"/>
  • delay:指每个Item的动画开始延时,取值是android:animation所指定动画时长的倍数,取值类型可以是float类型,也可以是百分数,默认是0.5,即一个Item的动画会在上一个item动画完成后延时单次动画时长的一倍时间开始,即延时1000毫秒后开始。
  • animationOrder:指viewGroup中的控件动画开始顺序,取值有normal(正序)、reverse(倒序)、random(随机)
  • animation:指定每个item入场所要应用的动画。仅能指定res/aim文件夹下的animation定义的动画,不可使用animator动画。

LayoutAnimation的代码实现 – LayoutAnimationController

//代码设置通过加载XML动画设置文件来创建一个Animation对象;Animation animation= AnimationUtils.loadAnimation(this,R.anim.slide_in_left);   LayoutAnimationController controller = new LayoutAnimationController(animation); //得到一个LayoutAnimationController对象;        controller.setOrder(LayoutAnimationController.ORDER_REVERSE);   //设置控件显示的顺序;controller.setDelay(0.3f);  //设置控件显示间隔时间;mListView.setLayoutAnimation(controller); //为ListView设置LayoutAnimationController属性;mListView.startLayoutAnimation(); // 启动动画

gridLayoutAnimation标签和 GridLayoutAnimationController

GridLayoutAnimation的XML实现——gridLayoutAnimation

<?xml version="1.0" encoding="utf-8"?><gridLayoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"    android:rowDelay="75%"    android:columnDelay="60%"    android:directionPriority="none"    android:direction="bottom_to_top|right_to_left"    android:animation="@android:anim/slide_in_left"/>
  • rowDelay:每一行动画开始的延迟。与LayoutAnimation一样,可以取百分数,也可以取浮点数。取值意义为,当前android:animation所指动画时长的倍数。
  • columnDelay:每一列动画开始的延迟。取值类型及意义与rowDelay相同。
  • directionPriority:方向优先级。取值为row,collumn,none,意义分别为:行优先,列优先,和无优先级(同时进行);具体意义,后面会细讲
  • direction: gridview动画方向。 取值有四个:
    left_to_right:列,从左向右开始动画
    right_to_left :列,从右向左开始动画
    top_to_bottom:行,从上向下开始动画
    bottom_to_top:行,从下向上开始动画
    这四个值之间可以通过“|”连接,从而可以取多个值。很显然left_to_right和right_to_left是互斥的,top_to_bottom和bottom_to_top是互斥的。如果不指定 direction字段,默认值为left_to_right | top_to_bottom;即从上往下,从左往右。
  • animation: gridview内部元素所使用的动画。

GridLayoutAnimation的代码实现——GridLayoutAnimationController

Animation animation = AnimationUtils.loadAnimation(MyActivity.this,R.anim.slide_in_left); // 加载动画GridLayoutAnimationController controller = new GridLayoutAnimationController(animation);controller.setColumnDelay(0.75f); // 每一列动画开始的延迟controller.setRowDelay(0.5f); // 每一行动画开始的延迟controller.setDirection(GridLayoutAnimationController.DIRECTION_BOTTOM_TO_TOP|GridLayoutAnimationController.DIRECTION_LEFT_TO_RIGHT); // gridview动画方向controller.setDirectionPriority(GridLayoutAnimationController.PRIORITY_NONE); // 方向优先级grid.setLayoutAnimation(controller);grid.startLayoutAnimation();

Activity Transitions

启动Activity时设置动画:

Intent i = new Intent(MainActivity.this, SecondActivity.class);startActivity(i);overridePendingTransition(R.anim.right_in, R.anim.left_out);

退出Activity时设置动画:

    @Override    public void onBackPressed() {        finish();        overridePendingTransition(R.anim.left_in, R.anim.right_out);    }

亲测有用

Modifying the Default Transitions

<!-- Customize `android:windowAnimationStyle` for theme --><style name="AppTheme" parent="AppBaseTheme">    <!-- ... -->    <item name="android:windowAnimationStyle">@style/CustomAnimation.Activity</item></style><style name="CustomAnimation.Activity" parent="@android:style/Animation.Activity">     <item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>    <item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>    <item name="android:activityCloseEnterAnimation">@android:anim/slide_in_left</item>    <item name="android:activityCloseExitAnimation">@android:anim/slide_out_right</item></style>

   试过之后发现activityOpen的动画有作用,activityClose的动画却不起作用,尚不知道什么原因

Activity过渡动画实例

下面是一些完整的Activity过渡动画实例:
Card Flip Animation
Vine Activity Transition
Sliding In From Left Animation
Sliding Drawer Animation

系统动画的duration常量

这些常量位于sdk中的data/res/values/config.xml中。

  <!-- The duration (in milliseconds) of a short animation. -->    <integer name="config_shortAnimTime">200</integer>    <!-- The duration (in milliseconds) of a medium-length animation. -->    <integer name="config_mediumAnimTime">400</integer>    <!-- The duration (in milliseconds) of a long animation. -->    <integer name="config_longAnimTime">500</integer>    <!-- The duration (in milliseconds) of the activity open/close and fragment open/close animations. -->    <integer name="config_activityShortDur">150</integer>    <integer name="config_activityDefaultDur">220</integer>

参考:

Animation动画详解(Animation系列讲的非常细,图文并茂)
Animations (codepath上面的教程)

0 0