我想通过为每个用户输入增加延迟来减少对Google Places API的请求,但是我不确定如何实现这一点。这通常是我为等待用户输入的EditText添加延迟的方法:
editTextEmail.addTextChangedListener(new TextWatcher() {
final Handler handler = new Handler();
Runnable runnable;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
isEmailValid = false;
textInputLayoutEmail.setError(null);
enableDisableButton();
handler.removeCallbacks(runnable);
}
@Override
public void afterTextChanged(Editable s) {
runnable = new Runnable() {
@Override
public void run() {
callGooglePlacesAPI()
}
};
handler.postDelayed(runnable, 1000);
}
});
这是我用来调用Google PLaces API的代码:
editTextLocation.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
editTextLocation.setShowSoftInputOnFocus(false);
searchLocation();
}
}
});
public void searchLocation(){
try
{
editTextLocation.clearFocus();
//hide soft keyboard
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(getActivity());
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
}catch (Exception e){
e.printStackTrace();
}
}
有没有办法做到这一点?请帮助提供建议。谢谢。