アンドロイド学習ノートの動画(下)


一、内容の概要
本編は属性アニメーションに重点を置いて、1篇のアンドロイド学習ノートのアニメーション(上)に続いて、以下の内容を含みます-属性アニメーション
     - ObjectAnimator    
     - ValueAnimator    
     - PropertyValuesHolder    
     - ViewPropertyAnimator    
     - AnimatorSet   

-補間と評価の概要
二、属性アニメーション
プロパティアニメーションの概要
-       API11       , android2.3      nineoldandroids   。
-            view     。 view        view     。
-             ,       view,           。

ViewPropertyAnimatorの使用
1.例
  @TargetApi(Build.VERSION_CODES.KITKAT)
    public void animate(View view) {
        final ViewPropertyAnimator animator = view.animate().x(200).y(300).alphaBy(-0.5f).rotationBy(60f).setInterpolator(new BounceInterpolator()).scaleXBy(0.3f).xBy(20).setDuration(2000);
        Log.e("TAG", view.getTranslationX() + " : " + view.getX());
        animator.setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                animator.alpha(1f).xBy(100).scaleY(2f).translationY(100).setDuration(3000).setInterpolator(new CycleInterpolator(5)).start();
                Log.e("TAG", "animating...");
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        //       api>19
// animator.setUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
// @Override
// public void onAnimationUpdate(ValueAnimator animation) {
//
// }
// });
        animator.start();

    }

2.解析の使用
1、ViewPropertyAnimatorオブジェクトを取得する
  view.animate()    ViewPropertyAnimator  animator

2、animatorでviewの属性を変える
animator.alpha(1f).xBy(100).scaleY(2f).translationY(100).setDuration(3000).setInterpolator(new CycleInterpolator(5));   

メソッドの解析:
     * x(),y()      view x,y       ,    
     * xBy(offset),yBy(offset),view x,y       ,   (offset),         ,    (alphaBy,translationXBy()   )
     * translationX(),translationY()    view translationX,translationY ,    
     * rotation()   view      
     * scaleX(),scaleY()   
     * setInterpolator()      
     * withStartAction(Runnable runnable)          API level 16
     * withEndAction(Runnable runnable)         ,             API level 16

注意:
    1、translationX    view x      (offset,    ,    ),x  view x  
    2、    start()  ,        ,      ,      start  

3、アニメーションの実行を傍受する
- animator.setListener          
    - onAnimationStart       
    - onAnimationEnd        
    - onAnimationCancel       
    - onAnimationRepeat      

- animator.setUpdateListener       ,         api>=19

4、Activity終了時にアニメーションを停止し、メモリ漏れを防止する
 @Override
    protected void onDestroy() {
        super.onDestroy();
        if (animator != null) {
            animator.cancel();
            animator = null;
        }
    }

ObjectAnimatorの使用
/** * ObjectAnimator * * @param view */
    public void objectAnimator(final View view) {
        final ObjectAnimator animator = ObjectAnimator.ofFloat(view, "scaleX", 1, 0.5f, 1);
        animator.addListener(new Animator.AnimatorListener() {   //       
            @Override
            public void onAnimationStart(Animator animation) {
                ObjectAnimator.ofFloat(view, "scaleY", 1, 0.5f, 1).setDuration(1000).start();
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.setDuration(1000).start();

    }

解析の使用
ObjectAnimator ValueAnimator    ,  Animation  ,              ,   of     view     ,
  • 一般的なofメソッド
    - ofArgb(Object target, String propertyName, int... values)
    - ofFloat(Object target, String propertyName, float... values)
    - ofInt(Object target, String propertyName, int... values)
    - ofObject(Object target, String propertyName,TypeEvaluator evaluator, Object... values)
    - ofPropertyValuesHolder(Object target,PropertyValuesHolder... values)
    
  • offXXX方法分析
         target:       view   
         propertyName:     ,  alpha,scaleX,scaleY,rotationX,rotationY,translationX,translationY
         values:           ,  ofFloat(targetView,"alpha",0,1);      0 1
    
  • PropertyValuesHolderの使用PropertyValuesHolderは設定した属性変化効果を一時的に記憶し、最後にview
  • に一緒に設定することができる.
     /** * PropertyValuesHolder    * @param view */
        public void propertyValuesHolder(View view) {
    
            final PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1, 0.5f, 1);
            final PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1, 0.5f, 1);
            final PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1, 0.5f, 1);
            final ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(ivBall, alpha, scaleX, scaleY);
            animator.setDuration(1000).start();
    
        }

    4.アニメーションリスニングの設定
    - addListener         ,         ,  ,  ,  
    - addUpdateListener        ,
    - addPauseListener           
    

    AnimatorListener Adapterを使用して選択的にリスニングできます
    animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                }
            });

    5.xmlの書き方
    <?xml version="1.0" encoding="utf-8"?>
    <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:duration="1000" android:propertyName="scaleX" android:valueFrom="1" android:valueTo="0.5f" android:valueType="floatType"></objectAnimator>

    6.メモリ漏れ防止
        Activity       ,      ,  cancel    、  
    

    7.使用原則
      ObjectAnimator    ,1、    view   (property)  set get  ,2、  set   view         ,      
    

    8.任意のオブジェクトに対してアニメーションを行う以上の使用原則に対して1つが満たさないとアニメーションを無効にし、公式に3つの解決策を与える
    1、        ,       set get  
    2、           ,      set get  
    3、  ViewAnimator,      ,         
    

    ValueAnimatorの使用
    ValueAnimator  ObjectAnimator  ,          ,             ,       ,           
    

    使用例
    public void valueAnimator(final View view) {
            final ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
            valueAnimator.setDuration(1000);
            valueAnimator.start();
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    final float fraction = animation.getAnimatedFraction();
                    Log.e("TAG", "fraction=" + fraction);
                    view.setTranslationY((float) (Math.sin(fraction*2*3.14159) * 200));
                    view.setTranslationX((float) (Math.sin(fraction*2*3.14159) * 200));
                }
            });
        }

    解析の使用
    1、よくあるofXXX方法
    ofArgb(int... values)
    ofFloat(float... values)
    ofInt(int... values)
    ofPropertyValuesHolder(PropertyValuesHolder... values)
    ofObject(TypeEvaluator evaluator, Object... values)
    

    2、リスニングの設定(ObjectAnimatorと同じ)3、xmlでValueAnimatorを定義する
    <?xml version="1.0" encoding="utf-8"?>
    <animator xmlns:android="http://schemas.android.com/apk/res/android" android:duration="1000" android:valueFrom="1" android:valueTo="0" android:valueType="floatType">
    
    </animator>

    4、javaコードにアニメーションをロードする
    final Animator animator = AnimatorInflater.loadAnimator(AnimatorActivity.this,R.animator.animator_value);
    

    5、評価器と補間器の設定も可能
     valueAnimator.setEvaluator(new FloatEvaluator());
     valueAnimator.setInterpolator(new AccelerateInterpolator());
    

    AnimatorSetの使用
    使用例
    1.javaコードの使用
        public void set(View view) {
            AnimatorSet set = new AnimatorSet();
            final ObjectAnimator scaleX = ObjectAnimator.ofFloat(ivBall, "scaleX", 1, 0.5f, 1);
            final ObjectAnimator scaleY = ObjectAnimator.ofFloat(ivBall, "scaleY", 1, 0.5f, 1);
            final ObjectAnimator translationX = ObjectAnimator.ofFloat(ivBall, "translationX", 0, 100, 0);
            final ObjectAnimator translationY = ObjectAnimator.ofFloat(ivBall, "translationY", 0, 100, 0);
            final ObjectAnimator rotationX = ObjectAnimator.ofFloat(ivBall, "rotationX", 0, 360);
            final ObjectAnimator rotationY = ObjectAnimator.ofFloat(ivBall, "rotationY", 0, 360);
            final ObjectAnimator alpha = ObjectAnimator.ofFloat(ivBall, "alpha", 1, 0.5f, 1);
    //        set.playTogether(scaleX, scaleY, translationX, translationY, rotationX, rotationY, alpha); //   
    //        set.playSequentially(scaleX, scaleY, translationX, translationY, rotationX, rotationY, alpha); //   
            set.play(scaleX).with(scaleY).with(translationX).with(translationY).before(rotationX);
            set.play(rotationX).with(rotationY).after(alpha); //      
    
            set.setDuration(2000).start();
        }

    2.xmlでアニメーションを定義する
    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android" android:ordering="sequentially">
        <objectAnimator  android:duration="1000" android:propertyName="scaleX" android:valueFrom="0" android:valueTo="1" android:valueType="floatType" />
        <objectAnimator  android:duration="1000" android:propertyName="scaleY" android:valueFrom="0" android:valueTo="1" android:valueType="floatType" />
        <objectAnimator  android:duration="1000" android:propertyName="alpha" android:valueFrom="0" android:valueTo="1" android:valueType="floatType" />
    </set>

    Javaコードで定義されたアニメーションを使用する
    final Animator set = AnimatorInflater.loadAnimator(context,R.animator.animator_set);
            set.setTarget(target);
            set.start();

    3、リスニングの追加(同様、3種類のリスニング方式)
    解析の使用
      playTogether         ,playSequentially        ,
      play    with、before、after          ,with         ,before、after        /         
    

    補間器と推定器の浅い分析
    補間器(TimeInterpolator)
    1、補間器の概念
                     ,         ,        ,  ,  ,     。                        。
    

    2、一般的な補間器
     OvershootInterpolator@android:anim/overshoot_interpolator                  
     AccelerateDecelerateInterpolator@android:anim/accelerate_decelerate_interpolator      
     AccelerateInterpolator@android:anim/accelerate_interpolator  
     AnticipateInterpolator@android:anim/anticipate_interpolator            
     AnticipateOvershootInterpolator@android:anim/anticipate_overshoot_interpolator                   
     DecelerateInterpolator@android:anim/decelerate_interpolator  
     LinearInterpolator@android:anim/linear_interpolator  
     BounceInterpolator@android:anim/bounce_interpolator        
     CycleInterpolator@android:anim/cycle_interpolator    
    

    3、CycleInterpolatorソースコードの分析
    ソースコードから補間器が入力した値と戻り値の関係式は、(float)(Math.sin(2*mCycles*Math.PI*input))であり、入力が大きくなると出力値がsin曲線値と交差し、必要なcycle効果を形成する
    @HasNativeInterpolator
    public class CycleInterpolator extends BaseInterpolator implements NativeInterpolatorFactory {
        public CycleInterpolator(float cycles) {
            mCycles = cycles;
        }
    
        public CycleInterpolator(Context context, AttributeSet attrs) {
            this(context.getResources(), context.getTheme(), attrs);
        }
    
        /** @hide */
        public CycleInterpolator(Resources resources, Theme theme, AttributeSet attrs) {
    
        }
    
        public float getInterpolation(float input) {
            return (float)(Math.sin(2 * mCycles * Math.PI * input));
        }
    
        private float mCycles;
    
    }
    

    4、カスタム補間器カスタムInterpolatorクラスInterpolatorを実現し、getInterpolation方法を実現すればよい
    簡単な例:
    package com.yu.propertyanimator;
    
    import android.annotation.TargetApi;
    import android.os.Build;
    import android.view.animation.Interpolator;
    
    /** * Created by pecu on 2016/08/27. */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    public class MyInterpolator implements Interpolator {
    
        @Override
        public float getInterpolation(float input) {
            return (float) Math.abs(Math.sin(input * Math.PI));  //     
        }
    }
    

    評価器(TypeEvaluator)
                            
    

    1、TypeEvealuatorインタフェースTypeEvealuatorインタフェースを見てみると、fractionで現在の値を推定するための抽象的な方法evaluateが1つしかないことが分かった.
    
    package android.animation;
    
    public interface TypeEvaluator<T> {
    
        /**
         * This function returns the result of linearly interpolating the start and end values, with
         * <code>fraction</code> representing the proportion between the start and end values. The
         * calculation is a simple parametric calculation: <code>result = x0 + t * (x1 - x0)</code>,
         * where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>,
         * and <code>t</code> is <code>fraction</code>.
         *
         * @param fraction   The fraction from the starting to the ending values
         * @param startValue The start value.
         * @param endValue   The end value.
         * @return A linear interpolation between the start and end values, given the
         *         <code>fraction</code> parameter.
    
        public T evaluate(float fraction, T startValue, T endValue);
    
    }
    

    2、FloatEvaluatorソースコードを見ると、evaluateメソッドの戻り値はこのような式によって計算されたresult=x 0+t*(x 1-x 0)であることがわかる.
    package android.animation;
    
    public class FloatEvaluator implements TypeEvaluator<Number> {
    
        /** * @param fraction The fraction from the starting to the ending values * @param startValue The start value; should be of type <code>float</code> or * <code>Float</code> * @param endValue The end value; should be of type <code>float</code> or <code>Float</code> * @return A linear interpolation between the start and end values, given the * <code>fraction</code> parameter. */
    
        public Float evaluate(float fraction, Number startValue, Number endValue) {
            float startFloat = startValue.floatValue();
            return startFloat + fraction * (endValue.floatValue() - startFloat);
        }
    }

    3、カスタムTypeEvaluator
              ,     TypeEvaluator  ,   evaluate    
    

    簡単なカスタムTypeEvaluator
    package com.yu.propertyanimator;
    
    import android.animation.TypeEvaluator;
    import android.graphics.Point;
    
    /** * Created by pecu on 2016/08/27. */
    public class MyEvaluator implements TypeEvaluator<Point> {
        Point point;
    
        @Override
        public Point evaluate(float fraction, Point startValue, Point endValue) {
            if (point == null) {
                point = new Point();
                point.x = (int) (startValue.x + fraction * (endValue.x - startValue.x));
                point.y = (int) (startValue.y + fraction * (endValue.y - startValue.y));
            } else {
                point.x = (int) (startValue.x + fraction * (endValue.x - startValue.x));
                point.y = (int) (startValue.y + fraction * (endValue.y - startValue.y));
            }
            return point;
        }
    }
    

    4、カスタムEvaluatorを使う
    /** *            * @param view */
        public void evaluate(View view) {
            final ValueAnimator valueAnimator = ValueAnimator.ofObject(new MyEvaluator(), new Point(0, 0), new Point(0, screenHeight - 2*ivBall.getHeight()));
            valueAnimator.setInterpolator(new BounceInterpolator());
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    Point point = (Point) animation.getAnimatedValue();
                    ivBall.setX(point.x);
                    ivBall.setY(point.y);
                }
            });
            valueAnimator.setDuration(1000);
            valueAnimator.start();
    
        }

    ソースのダウンロード