最近有类似的需求,这就是我为达到预期结果所做的
// create a class-scope variable to track the most recent query
private String lastQuery;
private GeoDataClient geoDataClient;
// wrap the geoDataClient.getAutocompletePredictions in a class to associate the prediction results with the query that triggered the call
class AutocompletePredictor {
String query;
AutocompletePredictor(String query) {
this.query = query;
}
Task<AutocompletePredictionBufferResponse> getPredictions(LatLngBounds bounds, AutocompleteFilter typeFilter) {
return geoDataClient.getAutocompletePredictions(query, bounds, typeFilter);
}
}
// modify your method that triggers the autocomplete filter
void filterAutocomplete(String constraint) {
// update lastQuery every time this method is called
lastQuery = constraint;
// Submit the query to the autocomplete API and retrieve a PendingResult that will contain the results when the query completes.
final AutocompletePredictor predictor = new AutocompletePredictor(constraint);
Task<AutocompletePredictionBufferResponse> results = predictor.getPredictions(bounds, typeFilter);
results.addOnSuccessListener(autocompletePredictions -> {
// checks if the query for this filter is same as the most recent query issued to this method
if (autoCompletePredictionsListener != null && predictor.query.equals(lastQuery)) {
autoCompletePredictionsListener.onAutoCompleteSuccess(autocompletePredictions);
}
autocompletePredictions.release();
});
}
编辑:用户键入时延迟调用...
而不是每次 EditText 的内容更改时调用自动完成方法(可以是每次用户键入字符时),而是安排自动完成调用等待一段时间之前实际执行。如果在等待时间过去之前 EditText 内容再次发生变化,请取消之前的计划并重新计划。
editText.addTextChangedListener(new TextWatcher() {
int delayMilliseconds = 500;
Handler handler = new Handler();
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void afterTextChanged(Editable editable) {
final String constraint = editable.toString();
// remove all delayed/pending tasks set in the last 500 milliseconds
handler.removeCallbacksAndMessages(null);
// setup a new delayed task to execute after 500 milliseconds
handler.postDelayed(new Runnable() {
@Override
public void run() {
filterAutocomplete(constraint);
}
}, delayMilliseconds);
}
});