由字符显示文字动画Android的字符字符、文字、动画、Android

2023-09-12 01:40:27 作者:忘川河畔

任何人都知道执行的动画,什么是必须做的任何有效的方法来显示文本中的字符?这样的:

Anyone knows any efficient method of perform an animation that what is has to do is to display a text, character by character?, like:

T 钍 氏 这 这是我 这是 ......

T Th Thi This This i This is ...

等等。

谢谢!

推荐答案

这可能不是最完美的解决方案,但最简单的可能是的TextView 快速子类,一个处理程序的更新文本,每隔一段时间,直到显示完整的序列:

This may not be the most elegant solution, but the simplest is probably a quick subclass of TextView with a Handler that updates the text every so often until the complete sequence is displayed:

public class Typewriter extends TextView {

    private CharSequence mText;
    private int mIndex;
    private long mDelay = 500; //Default 500ms delay


    public Typewriter(Context context) {
        super(context);
    }

    public Typewriter(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private Handler mHandler = new Handler();
    private Runnable characterAdder = new Runnable() {
        @Override
        public void run() {
            setText(mText.subSequence(0, mIndex++));
            if(mIndex <= mText.length()) {
                mHandler.postDelayed(characterAdder, mDelay);
            }
        }
    };

    public void animateText(CharSequence text) {
        mText = text;
        mIndex = 0;

        setText("");
        mHandler.removeCallbacks(characterAdder);
        mHandler.postDelayed(characterAdder, mDelay);
    }

    public void setCharacterDelay(long millis) {
        mDelay = millis;
    }
}

您可以使用这个在活动像这样:

You can then use this in an Activity like so:

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Typewriter writer = new Typewriter(this);
        setContentView(writer);

        //Add a character every 150ms
        writer.setCharacterDelay(150);
        writer.animateText("Sample String");
    }
}

如果你想要一些添加了每个字母的动画效果,也许看看子类化 TextSwitcher 代替。

If you want some animation effects with each letter added, perhaps look at subclassing TextSwitcher instead.

希望帮助!