1.导入依赖
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.12'
2.自定义TextView
public class JumpShowTextView extends 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();
}
}
);
}
private void stop() {
if (mDisposable != null && !mDisposable.isDisposed()) {
mDisposable.dispose();
}
}
}