简体   繁体   中英

How to animate a substring in Android?

I am wondering, is there a way to animate a substring in Android?

Suppose I have a string "I have 3 Apples."

I want to animate just the numerical part of the string, like scale up or maybe zoom the text view.

I recommend using a SpannableStringBuilder and a ValueAnimator for the text size.

String text = "your string";

String animTarget = "animation target");


final SpannableStringBuilder sBuilder = new SpannableStringBuilder(text);

int index = text.indexOf(animTarget);

float size;

RelativeSizeSpan textSize;


TextView view;

ValueAnimator animator = ValueAnimator.ofFloat(startingTextSize, endingTextSize);
animator.setDuration(duration);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {

                    size = (float) animation.getAnimatedValue();

                    textSize = new RelativeSizeSpan(size);

                    sBuilder.setSpan(textSize, // Span to add
                    index, // Start of the span (inclusive)
                    index+1, // End of span           
                     Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Do not extend);

                    view.setText(sBuilder)
        }
    });
 )

Basic idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM