我正在尝试实现一个SearchAutoComplete,它将在'实时'中显示http请求的结果,而无需实际按下搜索按钮。
我正在更新相应的适配器(获取正确的数据)。然而,只要我不重新发送请求,自动建议就不会再次弹出。因此,新适配器仅在适配器中已存在查询数据时才第二次工作。
我只需要一种方法来强制适配器数据立即更新适配器后显示。
这是一些代码:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tab_search, menu);
MenuItem searchMenu = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchMenu.getActionView();
// Get SearchView autocomplete object.
mSearchAutoComplete = mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
// Listen to search view item on click event.
mSearchAutoComplete.setOnItemClickListener((adapterView, view, itemIndex, id) -> {
//Index in adapter corresponds to index in searchResults, pass index
updateFromSearch(itemIndex);
if( ! mSearchView.isIconified()) {
mSearchView.setIconified(true);
}
searchMenu.collapseActionView();
});
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.d(TAG,"onQueryTextSubmit");
ApiManager.search(SearchActivity.this, query);
return false;
}
//https://stackoverflow.com/a/35268540
Handler handler = new Handler(Looper.getMainLooper());
Runnable workRunnable;
@Override
public boolean onQueryTextChange(String newText) {
Log.d(TAG,"onQueryTextChange");
if (newText.length() > 3) {
handler.removeCallbacks(workRunnable);
workRunnable = () -> ApiManager.search(SearchActivity.this, newText);
handler.postDelayed(workRunnable, 1000);
}
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
和适配器更新
private void updateSearchViewAdaper(List<String> data) {
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, data);
mSearchAutoComplete.setAdapter(adapter);
//mSearchAutoComplete.invalidate();
/* I want this adapter to be shown immediatly after it has been updated */
}
以及成功搜索的回调:
@Override
public void onSearchSuccess(List<SearchResult> searchResults) {
mSearchResults = searchResults;
List<String> searchSuggestions = new ArrayList<>();
for (SearchResult result : searchResults) {
searchSuggestions.add(result.toString());
}
updateSearchViewAdaper(searchSuggestions);
}