Android动画精讲一:从setTranslationX谈属性动画和view动画的区别

Android之动画精讲一:从setTranslationX谈属性动画和view动画的区别 转载:http://blog.csdn.net/yanzi1225627/article/details/47850471 最近又用到了动画,决定把几次项目里用到的动画走过的弯路总结一下,顺便梳理下android的动画体系。众所周知,android动画分三类:一是View 动画,又叫Tween动画,二是frame 动画(帧动画),又叫drawable 动画,三是属性动画,即property an 阅读详情
From:http://blog.youkuaiyun.com/yanzi1225627/article/details/47850471

       最近又用到了动画,决定把几次项目里用到的动画走过的弯路总结一下,顺便梳理下Android的动画体系。众所周知,android动画分三类:一是View 动画,又叫Tween动画,二是frame 动画(帧动画),又叫drawable 动画,三是属性动画,即property animation. 
       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.
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

       上面是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);
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

       之所以说有时需要新建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
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

       总结: 
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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@android:color/holo_green_light"
        android:orientation="vertical">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_start_anim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="属性动画" />
    <Button
        android: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="复位" />

    <Button
        android: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>
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

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;

    @Override
    protected 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);

    }


    @Override
    public 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() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public 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);
    }
}
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130

用到了一个辅助类获得屏幕的宽高和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.0
        densityDpi = metrics.densityDpi;  //120 160 240 320 480
        Log.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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

运行界面: 
这里写图片描述

       大概说下里面核心的几个函数: 
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);
    }
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        transAnim.setDuration(300);
        transAnim.start();;
    }
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

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();
        }
    }
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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

private void resetPos(){
        ViewHelper.setTranslationX(text, 0);
    }
   
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

       直接将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() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                updateParams();
            }

            @Override
            public 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);
    }
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

       即使用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
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

       如果为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动画最合适!

The 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.youkuaiyun.com/detail/yanzi1225627/9034125 
--—–--本文系原创,转载注明作者yanzi1225627

DEAP数据集实战指南:从脑电信号到情绪分类的完整流程解析 本文提供了DEAP数据集在脑电信号情绪识别领域的完整实战指南。详细解析了数据下载、结构理解、频带功率特征提取等核心步骤,并演示了如何构建和评估机器学习分类模型,为研究者实现从原始脑电信号到情绪分类的完整流程提供了清晰路径。 阅读详情

相关推荐

香橙派OPi 6系列选型指南:RK3588与RK3588S开发板深度对比

开发板选型是嵌入式系统设计的关键环节,尤其在边缘计算和AI推理等场景中,芯片的差异直接影响硬件架构。瑞芯微RK3588及其精简版RK3588S是当前高端开发板的核心方案,两者在PCIe通道、显示输出和SATA支持上存在显著区别。理解这些原理,有助于工程师根据项目需求快速匹配产品。香橙派OPi 6系列基于这两款芯片,衍生出OPi 6、OPi 6 Pro与OPi 6 Max三种形态:紧凑型适合嵌入式门禁与AI盒子,Pro版凭借双屏异显和PCIe 3.0满足收银机与视频分析,Max的双2.5G网口和大内存则面向轻

weixin_29185167的博客 229

Android动画View的setX跟setTranslationX区别结合源码解析

以TextView为例我们看看,先看一下我的xml: <TextView android:id="@+id/tv_test" android:layout_width="200dp" android:layout_height="50dp" android:layout_marginLeft="20dp" android:text="Test"/> 看一下原图: 然后我们调一下setX看看:

SunshineBoy的博客 6339

基于IP2369与STM32的45W双向PD移动电源设计

USB PD(Power Delivery)是一种面向高功率、智能协商的通用快充协议,其核心在于通过BMC编码在CC线上完成供电能力(PDO)动态匹配与电压/电流精准调控。IP2369作为高度集成的PD协议管理芯片,内置PHY、协议引擎与MOSFET驱动,可卸载MCU实时通信压力;而STM32F103系列凭借低功耗STOP模式与丰富外设,成为电源状态管理与用户交互的理想协处理器。该组合显著提升系统鲁棒性与能效比,适用于便携式移动电源、嵌入式备用电源及PD协议教学验证等场景。本文围绕IP2369配置电阻精度、

weixin_42608299的博客 519

offsetLeftAndRight()和setTranslationX()的区别

前言 view的最终展示效果由view.x和view.y来决定 view.x = mLeft + translationX view.y = mRight + tranlationY 异同 相同点: 两种方式都可以移动view。 不同点: offsetLeftAndRight(offset: Int)修改的是view的mLeft或mRight,其内部传入的是相对值。 setTranslationX(translation: Int)修改的是view的translation值,传入的是tra

放下矜持的博客 1354

沧小海深入剖析xilinx的GTP/GTX核,掌握高速串行收发机制——第六章 接收端结构及功能说明

总目录在这哦~ https://blog.csdn.net/z123canghai/article/details/107700878 第六章 接收端结构及功能说明 子目录 6.1 RX的模拟前端 6.2 RX的OOB信号 6.3 RX的均衡器 6.4 RX的CDR 时钟数据恢复 6.5 RX时钟输出结构 6.6 RX 的极性控制 6.7 RX 的PRBS 6.8 Rx字节、字的对齐功能 6.9 Rx接收弹性缓冲区 6.10 Rx的时钟纠正 6.11 Rx接收通道绑定 6...

滄海的博客 1万+

HTPA 32x32d热成像传感器实战指南:从替代MLX90640到精准测温

本文为HTPA 32x32d热成像传感器提供了从硬件连接到精准测温的完整实战指南。针对MLX90640替代需求,详细解析了HTPA传感器的核心优势、IIC通信要点、EEPROM校准数据读取与解析、独特的块数据读取模式,并逐步拆解了五大温度补偿计算流程,旨在帮助开发者克服高开发门槛,实现稳定可靠的非接触式测温应用。

weixin_29279101的博客 317

View 的 translationX、 translationY , X、Y 和 Left、Top,Right、Bottom之间的关系

网上有不少人把view的坐标和点击事件的坐标 混为一谈 一、View的相关坐标和位置 先来看一张图,对这几个值有个大概了解,下面再进行详细的分析 先来了解一个概念: view动画不改变view的真实位置,就是肉眼看上去,view位置发生了变化,但是它的点击区域还是在原来的位置。 属性动画和setTranslationX/setTranslationY ,会改变显示位置和真实位置 上图...

qijingwang的博客 3597

audio框架学习-Audio_Flinger分析

文章目录一、代码位置二、audio服务启动2.1 main服务2.2 audioflinger添加到系统服务中2.3 audioflinger的对外接口 之前记录过audioTrack的笔记,这次继续参考audioFlinger相关的代码并做笔记; 参考文档:https://www.cnblogs.com/innost/archive/2011/01/15/1936425.html和https://blog.csdn.net/zyuanyun/article/details/60890534?spm=100

永不秃头的程序员的博客 2136

关于left,translationX,X

关于left,translationX,X

村口老张头的专栏 2625

【数据集3】高分辨率统计降尺度日值数据集NEX-GDDP的介绍与下载方法

对NEX-GDDP数据集进行介绍和下载说明

WW、forever的博客 2394

YOLOv11 改进 - Mamba | 集成Mamba-YOLO(AAAI 2025),Mamba-YOLOv11-B 替换骨干,破解全局依赖建模难题,实现高效实时检测

本文介绍Mamba YOLO,为图片物体识别提供了“又快又准”的新方案。传统CNN架构运行快但难以捕捉远距离关联物体,Transformer架构精度高但计算量呈平方级增长,而SSM虽计算量为线性级且能抓全局关联,但用于图片识别时细节定位不准。为此,Mamba YOLO做了三项关键优化:引入ODMamba骨干网络,解决自注意力的二次复杂度问题,且无需预训练;设计ODMamba宏观结构确定最佳阶段比例和缩放大小;采用多分支结构的RG块建模通道维度,解决SSM在序列建模中的不足。在COCO数据集测试中,其小版本推

魔改工程师的博客 859

Android动画精讲一 从setTranslationX谈属性动画和view动画的区别

Android动画精讲一 从setTranslationX谈属性动画和view动画的区别

hhduyc的博客 1860

手把手教你学simulink(85.6)--非线性控制:滑模控制场景实例:基于Simulink建模仿真的滑模控制(Sliding Mode Control, SMC)在无人机自主飞行控制系统中的应用

首先,在MATLAB命令窗口中定义系统的参数和状态空间模型。matlab深色版本% 系统参数m = 1.5;% 无人机质量 (kg)g = 9.81;% 重力加速度 (m/s^2)% 惯性矩阵 (kg*m^2)% 初始条件pos0 = [0;0;0];% 初始位置 (m)vel0 = [0;0;0];% 初始速度 (m/s)0;0];% 初始姿态角 (rad)0;0];% 初始角速度 (rad/s)

MHD0815的博客 656

Android View -- setTranslationX

通过此方法使View位置发生偏移,达到margin的作用却又不改变View的getLeft()的值。 恢复方法是setTranslationX(0),而不是上一次偏移量的相反数。 不过,通过getLocationInWindow(), getLocationOnScreen()获取到的位置是发生变化的,因此才能看到View的移动。 参考:Android动画精讲一:从setTr...

1929

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

View位置总结

为什么80%的码农都做不了架构师?>>> ...

weixin_33928467的博客 210

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

进阶 | View事件体系

这两天的面试,我发现很多东西我并没有了解其机制,只是停留在表面。 1. View位置参数 参数 含义 获取方式 (mLeft , mTop) (mRight , mBottom) 左上角点和右下角点相对于父容器的坐标 getXXX() x,y 可视View左上角的位置 getX/getY translationX,translationY ...

落红不是无情物 204

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

View 的 translationX、 translationY , X、Y 和 Left、Top,Right、Bottom

网上有不少人把view的坐标和点击事件的坐标 混为一谈 一、View的相关坐标和位置 先来看一张图,对这几个值有个大概了解,下面再进行详细的分析 先来了解一个概念: view动画不改变view的真实位置,就是肉眼看上去,view位置发生了变化,但是它的点击区域还是在原来的位置。 属性动画和setTranslationX/setTranslationY ,会改变显示位置和真实位置 上...

薛瑄的博客 1万+

android中动画区别是什么意思,Android动画View的setX跟setTranslationX区别结合源码解析...

Android动画View的setX跟setTranslationX区别结合源码解析Android动画View的setX跟setTranslationX区别结合源码解析以TextView为例我们看看,先看一下我的xml:android:id="@+id/tv_test"android:layout_width="200dp"android:layout_height="50dp"android:l...

weixin_33694136的博客 442

Android-区分 View 的 translationX、Y , X、Y 和 Left、Top,Right、Bottom

Android - 区分 View 的 translationX/Y , X/Y 和 Left/Top,Right/Bottom1. left,top,right,bottomView 的位置主要由它的四个顶点的位置来决定,分别对应 View 的四个属性:left top right bottom。 改变 View 的 translationX/Y,此时 View 的 x/y 变化,而 left/top 不变。

Duan的博客 4258

Android View的三种移动方式盘点

要使View在规定的时间中移动到指定的位置,我们会调用startScroll()方法,startScroll()是Scroller类中的方法,另外Scroller类中还有一个filing()方法也是很常用的,它主要是处理平滑的移动,一般营造滑动之后的惯性效果,使得View的移动更逼真。

hdxx2022的博客 649

Android视图坐标体系总结

如何获得任意一个View在屏幕中的坐标,如何获得一个View相对于父视图的位置,如果View的位置移动了会带来哪些影响,这一切其实都关乎于Android坐标体系的问题,那今天就对这些问题做个解析与总结。

ganklun的专栏 1258
上一篇: java当中的定时器的4种使用方式
下一篇: Android中Activity.this,getApplicationContext(),getBaseContext()和this详解
It_BeeCoder
博客等级 码龄10年 967粉丝 238原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值