我以同样的方式实现了我的应用程序的搜索功能。我使用 aTextWatcher
在用户键入时构建搜索结果。我保留了我的 AsyncTask 的参考来实现这一点。我的 AsyncTask 声明:
SearchTask mySearchTask = null; // declared at the base level of my activity
然后,在TextWatcher
每个字符输入的 , 中,我执行以下操作:
// s.toString() is the user input
if (s != null && !s.toString().equals("")) {
// User has input some characters
// check if the AsyncTask has not been initialised yet
if (mySearchTask == null) {
mySearchTask = new SearchTask(s.toString());
} else {
// AsyncTask is either running or has already finished, try cancel in any case
mySearchTask.cancel(true);
// prepare a new AsyncTask with the updated input
mySearchTask = new SearchTask(s.toString());
}
// execute the AsyncTask
mySearchTask.execute();
} else {
// User has deleted the search string // Search box has the empty string "" now
if (mySearchTask != null) {
// cancel AsyncTask
mySearchTask.cancel(true);
}
// Clean up
// Clear the results list
sResultsList.clear();
// update the UI
sResultAdapter.notifyDataSetChanged();
}