Android 打字机效果

1、导入Rxjava库

 implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
 implementation 'io.reactivex.rxjava2:rxjava:2.2.12'

2、自定义TextView

/**
 * 打字机效果
 * @author yi
 */
public class JumpShowTextView extends androidx.appcompat.widget.AppCompatTextView {
    public Disposable mDisposable;
    private String text;
    private StringBuilder stringBuilder;

    public JumpShowTextView(@NonNull Context context) {
        super(context);
    }

    public JumpShowTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public JumpShowTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void start(String text) {
        this.text = text;
        startView();
    }


    private void startView() {
        stringBuilder = new StringBuilder();
        mDisposable = Flowable.interval(100, TimeUnit.MILLISECONDS)
                .take(text.length())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                            stringBuilder.append(text.substring(aLong.intValue(), aLong.intValue() + 1));
                            setText(stringBuilder);
                            if (aLong == text.length() - 1) {
                                stop();
                            }
                        }
                );


    }

    public void stop() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

}