gpt4 book ai didi

java - 在 Edittext 上使用 setText 的 RxTextView.textChanges

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:32 24 4
gpt4 key购买 nike

RxTextView.textChanges(editText)
.map(CharSequence::toString)
.debounce(200, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(input -> {
output = //...do something with input
editText.setText(ouput)
}));

当我 setText(output) 它进入循环。要设置文本,我首先需要删除监听器,然后再次设置监听器。我如何使用 RxJava 来做到这一点?

最佳答案

When I setText(output) it goes in loop. To set the text I first need to remove listener and then set listener again. How can I do this using RxJava?

为了满足要求,我设法扩展了 RxBinding源码如下。

EditableTextViewTextObservable.java:

public class EditableTextViewTextObservable extends InitialValueObservable<CharSequence> {
private final TextView view;

EditableTextViewTextObservable(TextView view) {
this.view = view;
}

@Override
protected void subscribeListener(Observer<? super CharSequence> observer) {
EditableTextViewTextObservable.Listener listener = new EditableTextViewTextObservable.Listener(view, observer);
observer.onSubscribe(listener);
view.addTextChangedListener(listener);
}

@Override protected CharSequence getInitialValue() {
return view.getText();
}

final static class Listener extends MainThreadDisposable implements TextWatcher {
private final TextView view;
private final Observer<? super CharSequence> observer;

Listener(TextView view, Observer<? super CharSequence> observer) {
this.view = view;
this.observer = observer;
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void afterTextChanged(Editable s) {
if (!isDisposed()) {
view.removeTextChangedListener(this);
observer.onNext(s);
view.addTextChangedListener(this);
}
}

@Override
protected void onDispose() {
view.removeTextChangedListener(this);
}
}
}

EditableRxTextView.java:

public final class EditableRxTextView {
@CheckResult
@NonNull
public static InitialValueObservable<CharSequence> textChanges(@NonNull TextView view) {
return new EditableTextViewTextObservable(view);
}
}

用法:

EditableRxTextView.textChanges(editText)
.map(CharSequence::toString)
.debounce(200, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(input -> {
output = //...do something with input
editText.setText(ouput)
}));

关于java - 在 Edittext 上使用 setText 的 RxTextView.textChanges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50797759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com