LoginSignup
4
6

More than 5 years have passed since last update.

ValueAnimatorを使って、TextViewのtextColorをアニメーションさせる方法

Last updated at Posted at 2017-05-25

目的

TextViewのtextColor(文字色)をValueAnimatorでアニメーションさせたい。
例えば、背景色を黒から白にフェードアニメーションさせた時、テキスト色も白から黒にフェードさせるような動きをつけたり、
テキストをゆっくりとした点滅(明滅)させるような動きをつけたい。

実装

こんな感じで実装できる。(Activityにある場合)

final TextView textView = findViewById(R.id.textView);
int color1 = ResourcesCompat.getColor(getResources(), R.color.white, getTheme());
int color2 = ResourcesCompat.getColor(getResources(), R.color.black, getTheme());
ValueAnimator animator = new ValueAnimator(); // (1)
animator.setIntValues(color1, color2); // (2)
animator.setEvaluator(new ArgbEvaluator()); // (3)
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator anim) {
        int color = (Integer) anim.getAnimatedValue();
       textView.setTextColor(color);
    }
});

animator.setDuration(300);
animator.start();

補足

(1) ObjectAnimatorを使うよりもValueAnimatorの方がまとまる
(2) color1, color2は、getColorした値。colorのIDではない。
(3) ArgbEvaluatorをつかうことで、ARGB各値がアニメーションされる。

アニメーション途中で色を変える場合

トグルのボタンとか、アニメーション中にアニメーションが変わるときはこんな感じ。

private ValueAnimator mAnimator;

void changeColor(int colorId) {
    if (mAnimator != null) {
        mAnimator.cancel() // (4)
    }
    final TextView textView = findViewById(R.id.textView);
    int currentColor = textView.getCurrentTextColor(); // (5)
    int targetColor = ResourcesCompat.getColor(getResources(), colorId, getTheme());
    mAnimator = new ValueAnimator(); 
    mAnimator.setIntValues(currentColor, targetColor);
    mAnimator.setEvaluator(new ArgbEvaluator());
    mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator anim) {
            int color = (Integer) anim.getAnimatedValue();
           textView.setTextColor(color);
        }
    });

    mAnimator.setDuration(300);
    mAnimator.start();
}

補足

(4) 再生中のAnimatorを止める
(5) 今の文字色を取得する

Lolipop以降

API21以降(Lolipop以降)はコード省略できる。

// Android(API21未満)
ValueAnimator animator = new ValueAnimator();
animator.setIntValues(color1, color2);
animator.setEvaluator(new ArgbEvaluator());
// Android(API21以降)
ValueAnimator anim = ValueAnimator.ofArgb(color1, color2)

参考

4
6
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
4
6