我想在我的搜索视图中添加自动建议(不在操作栏中),此建议来自 GET API 调用。我解析对 POJO 类的响应。现在,是否有必要将建议存储在内容提供商中?或者我可以使用POJO类本身,如果可以的话,如何?感谢您的任何帮助。
你可以使用Textwatcher来实现这一点。
searchField.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(final Editable s) {
if (s.length() > 2) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("api call")
// fetch and show the result
}
} catch (MalformedURLException e) {
Log.e(((Object) this).getClass().getCanonicalName(), e.getMessage());
} catch (IOException e) {
Log.e(((Object) this).getClass().getCanonicalName(), e.getMessage());
} catch (JSONException e) {
Log.e(((Object) this).getClass().getCanonicalName(), e.getMessage());
}
}
});
}
}
});
我认为这就是你想要的..
这可能有助于您:
FilterEditText.addTextChangedListener(filterTextWatcher);
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//hide or show close icon based on text entered
try {
if (s.length() == 0) {
//not typed anything in the search box then load the adapter with default values or empty
initializeAdapter(mAirportCity);
}
} catch (Exception e) { e.printStackTrace(); }
//If user enters text to search, then call the api with entered text
onSearchTextChanged(s.toString());
}
};
public void onSearchTextChanged(String searchTxt) {
if (searchTxt == null || TextUtils.isEmpty(searchTxt) || searchTxt.length() < 2) {
return;
} else {
String url = "Your Base URL";
url= url + searchTxt.trim().replace(" ", "%20");
CJRVolley.getRequestQueue(getApplicationContext()).add(new CJRGsonGetRequest(url,
this, this, "Your Model Class here", null));
}
}
@Override
public void onResponse(IJRDataModel response) {
//in onresponse initialize the adapter here
}
}