LoginSignup
54
53

More than 5 years have passed since last update.

Androidでアニメーションしたい

Posted at

ValueAnimatorというものがあったので使ったメモ

ValueAnimator

http://developer.android.com/reference/android/animation/ValueAnimator.html
APIレベル11から使用することが可能になった。

ValueAnimatorの初期化

ValueAnimatorの場合、newでインスタンスを生成しない。
代わりにValueAnimator.ofFloatというクラスメソッドを呼び出してインスタンスを取得する。

例えばこんな感じ。

Animatorの初期化
ValueAnimator anim = ValueAnimator.ofFloat(0.f, 100.f);
// アニメーションの時間(3秒)を設定する
anim.setDuration(3000);
anim.start();

たったこれだけで3秒間で0.0から100.0まで変化するオブジェクトを起動できます。
実際にこれを使ってみると、こんな感じ。

Animatorの初期化2
ValueAnimator anim = ValueAnimator.ofFloat(0.f, 100.f);
// アニメーションの時間(3秒)を設定する
anim.setDuration(3000);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                invalidate();
            }
        });
anim.start();

ValueAnimatorの値が変化するタイミングでonAnimationUpdateが呼び出されるので、ここに任意の処理を書きます。
最後に、あるViewのonDraw内で上で定義したanimの値を使ってアニメーションを体感してみます。

drawSomethingView.java
protected void onDraw(Canvas canvas) {
    // 赤い背景
    canvas.drawColor(Color.RED);

    // だんだん大きくなる緑の円を書くよ
    float radius = (Float) (anim.getAnimatedValue());
    Paint p = new Paint();
    p.setColor(Color.GREEN);
    canvas.drawCircle(getWidth()/2, getHeight()/2, radius, p);
}

楽ちんだなあ。
それまではThreadを生成して、runの中でアニメーションさせる差分の計算させてた。シンドかった。
ValueAnimatorありがたやー

54
53
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
54
53