我有一个“编辑”文本,用于观察自动更新搜索页面的更改。在输入的每个字符上,都会触发观察程序,因此对于apple
这样的搜索查询,该查询会触发为
D/debug: a
D/debug: ap
D/debug: app
D/debug: appl
D/debug: apple
所以我用计时器添加了
2s
的延迟,日志看起来像D/debug: apple
D/debug: apple
D/debug: apple
D/debug: apple
D/debug: apple
在
2s
之后立即将它们一起触发。这是我的文字观察器,search_et.addTextChangedListener( object: TextWatcher{
override fun afterTextChanged(s: Editable?) {
val timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
Log.d("debug", "$s");
}
}, 2000)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
我要完成的任务是在2秒内从EditText获取一次值,在这种情况下我该怎么办才能正确处理?
最佳答案
使用处理程序概念,我们可以这样做。通过这种方式,我们可以限制号码。在编辑文本中实现搜索功能时的api调用数量。
Java:
private Handler textSearchHandler = new Handler(); //declare it as a global variable
et_FilterStopsFromListActivity_FilterETxt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
textSearchHandler.removeCallbacksAndMessages(null); //It will clear all previous callbacks
}
@Override
public void afterTextChanged(final Editable s) {
textSearchHandler.postDelayed(new Runnable() {
@Override
public void run() {
callApi();//do whatever you want to do
}
}
}, 2000);
}
});
Kotlin :
private var textChangedHandler = Handler() // declare it globally.
tie_password.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
textChangedHandler.postDelayed(runnable,2000)
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
textChangedHandler.removeCallbacksAndMessages(runnable)
}
})
var runnable = Runnable {
callApi() //do whatever you want to do here.
}
关于android - Android EditText观察者受API调用时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61968225/