【发布时间】:2021-08-27 11:58:55
【问题描述】:
好吧,我必须调用 api 从服务器获取数据并显示在 AutoCompleteTextView 中。我可以完美地获取该搜索结果,但问题是,当我在 AutoCompleteTextView 中输入单个字母时,每次执行 api 时,这都不是很好的用户体验,而且需要太多时间。
虽然,我已经创建了一些逻辑来在几秒钟后获取数据,但它只在我输入下一个字母时才有效。
String sec;
home_name_search.addTextChangedListener(new TextWatcher() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void afterTextChanged(Editable s) {
Format sdf = new SimpleDateFormat("ss");
if (s.length() >= 3) { // minimum 3 letters to execute api.
if (s.length() == 3) {
sec = sdf.format(new Date());
} else {
try {
SimpleDateFormat sdf2 = new SimpleDateFormat("ss");
String Cdate = sdf.format(new Date());
Date d1 = sdf2.parse(sec);
Date d2 = sdf2.parse(Cdate);
long CompareDate = d2.getTime() - d1.getTime();
if (CompareDate >= 3000) {
//here my api executes in AsyncTask.
sec = sdf.format(new Date());
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
});
【问题讨论】:
标签: java android android-studio android-layout autocompletetextview