目标 :
我想从 web 服务中获取一些字符串并用它们填充 AutoCompleteTextView。这很简单,但我真正想要的是在输入完成后开始搜索(调用 web 服务)。
我的意思是,例如,我输入了一些东西,输入完成后 3 秒,AutoCompleteTextView 将被填充并显示建议。
到目前为止我做了什么:
正如您在下面的代码中看到的,我使用 CountDownTimer 来实现这一点。我将它设置为 3 秒并在 OnTextChanged 中启动它。当用户键入时,我清除 CountDownTimer 并创建它的新实例并重新启动它。
因此,每当用户键入 - 每次按键时 - 我都会重置计数器。
之后,我在 CountDownTimer 的 OnFinish() 中调用我的方法——调用 web 服务并填充 AutoCompleteTextView。
问题 :
当我完成输入时,一切都按预期工作,正如我在调试模式下看到的那样。但建议不会出现在第一次搜索中。
我的意思是,它也可以工作,但 AutoCompleteTextView 不会仅在第一次填充数据。
笔记 :
我以同步和异步方式调用 web 服务。
counter=new MyCount(3000, 1000);
autoComplete.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable editable) {
if(isBackPressed){ //catch from KeyListener, if backspace is pressed don't invoke web service
isBackPressed=false;
return;
}
String newText = editable.toString();
searchText=newText;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(isBackPressed){
isBackPressed=false;
return;
}
counter.cancel();
counter=new MyCount(3000, 1000);
counter.start();
}
});
这是我的 CountDownTimer 类
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
invoke_webservice(searchText);
}
@Override
public void onTick(long millisUntilFinished) {
}
}
这是我以同步方式调用 web 服务的方法
public void invoke_webservice(String key){
try{
. //code to invoke webservice and populate string [] results
.
.
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,results);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
这是我以异步方式调用 web 服务的方法
class getJson extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... key) {
String newText = key[0];
. //code to invoke webservice and populate string [] results
.
.
runOnUiThread(new Runnable(){
public void run(){
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,results);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
}
提前致谢