hho*_*man 10 android autocomplete
我正在使用这个应用程序,用户可以在autoCompleteTextView中输入一个位置,它会根据此处描述的Google Places Api建议位置.
但是,如果用户在一段时间内停止输入,我想通过仅发送请求来限制应用程序发送的请求数量.有谁知道如何做到这一点?
Jan*_*kel 14
类似于这个答案,但略显简洁,没有引入额外的状态.您也不需要阈值检查,因为performFiltering仅在实际需要过滤时调用.
子类AutoCompleteTextView似乎是唯一的方法,因为你不能覆盖/替换TextWatcher添加的AutoCompleteTextView.
public class DelayAutoCompleteTextView extends AutoCompleteTextView {
public DelayAutoCompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
DelayAutoCompleteTextView.super.performFiltering((CharSequence) msg.obj, msg.arg1);
}
};
@Override
protected void performFiltering(CharSequence text, int keyCode) {
mHandler.removeMessages(0);
mHandler.sendMessageDelayed(mHandler.obtainMessage(0, keyCode, 0, text), 750);
}
}
Run Code Online (Sandbox Code Playgroud)
我已经找到了上述问题的解决方案,效果非常好。我通过以下方式扩展了 AutoCompleteTextView。如果有人知道如何进一步改进此代码,请告诉我。
public class MyAutoCompleteTextView extends AutoCompleteTextView {
// initialization
int threshold;
int delay = 750;
Handler handler = new Handler();
Runnable run;
// constructor
public MyAutoCompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void performFiltering(final CharSequence text, final int keyCode) {
// get threshold
threshold = this.getThreshold();
// perform filter on null to hide dropdown
doFiltering(null, keyCode);
// stop execution of previous handler
handler.removeCallbacks(run);
// creation of new runnable and prevent filtering of texts which length
// does not meet threshold
run = new Runnable() {
public void run() {
if (text.length() > threshold) {
doFiltering(text, keyCode);
}
}
};
// restart handler
handler.postDelayed(run, delay);
}
// starts the actual filtering
private void doFiltering(CharSequence text, int keyCode) {
super.performFiltering(text, keyCode);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2335 次 |
| 最近记录: |