Object animator not removing update listener android

元气小坏坏 提交于 2019-12-02 07:38:33

I see lot's of guys been looking at the post,meaning they got this issue too so i got the solution somehow fixed...Issue is that this damned ObjectAnimator when done inside an loop even with static method,each time is being created new reference to it.So you have to do something like this.Have an array list of object animators,on each call add items to array list.Whenever you want to stop it just simply loop through array and stop all object animators.Here is the code

private ArrayList<ObjectAnimator> objectAnimators = new ArrayList<>();
  public void startRainbowAnimation(Context context,
                                  final String textToShow,
                                  final TextView textViewToAttach) {
    stopCalled = false;
    AnimatedColorSpan span = new AnimatedColorSpan(context);
    final SpannableString spannableString = new SpannableString(textToShow);
    String substring = textToShow;
    int start = textToShow.indexOf(substring);
    int end = start + substring.length();
    spannableString.setSpan(span, start, end, 0);

    ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(
            span, animatedColorSpanFloatProperty, 0, 100);
    objectAnimator.setEvaluator(new FloatEvaluator());

    objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            System.gc();
            if (!stopCalled) {
                textViewToAttach.setText(spannableString);
            }
        }
    });
    objectAnimator.setInterpolator(new LinearInterpolator());
    objectAnimator.setDuration(DateUtils.MINUTE_IN_MILLIS * 3);
    objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
    objectAnimator.start();
    objectAnimators.add(objectAnimator);
}
objectAnimators here is an array list of object animators like this

And here is how you stop all of them to get ride of infinite update listener call firing.

 public void stopRainbowAnimation() {
    System.gc();
    stopCalled = true;
    if (!objectAnimators.isEmpty()) {
        for (int i = 0; i < objectAnimators.size(); i++) {
            ObjectAnimator eachAnimator = objectAnimators.get(i);
            eachAnimator.setRepeatCount(0);
            eachAnimator.end();
            eachAnimator.cancel();
            eachAnimator.removeAllListeners();
            eachAnimator.removeAllUpdateListeners();
        }
        objectAnimators.clear();
    }
}

Hope this will help someone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!