将 ArrayAdapter 转换为 CursorAdapter 以在 SearchView 中使用 [英] Converting an ArrayAdapter to CursorAdapter for use in a SearchView
问题描述
如何将静态数据的 ArrayAdapter
转换为 CursorAdapter
以在 SearchView
中使用建议侦听器?我已经从静态数据 (allString
)
How can I convert an ArrayAdapter<String>
of static data into a CursorAdapter
for using Suggestion Listener in SearchView
?
I have constructed the ArrayAdapter<String>
from static data (allString
)
ArrayAdapter<String> searchAdapter = new ArrayAdapter<String>(context, R.layout.listitem, allString);
我将它用于 MultiAutoCompleteTextView
,它在 API 级别低于 11 的设备上运行良好
and I use it for an MultiAutoCompleteTextView
which works fine in devices with API level less than 11
MultiAutoCompleteTextView findTextView.setAdapter(searchAdapter);
然而,我的目标 API 是 11 级,对于 API>10,我使用了一个 ActionBar
,我想在其中使用一个 SearchView.
However my target API is level is 11 and for API>10 I use an ActionBar
within which I would like to have a SearchView instead.
这是我尝试过的:它确实显示了带有嵌入式 SearchView
的 ActionBar
,但没有像 MultiAutoCompleteTextView
那样给出任何建议>.
Here's what I have tried: It does show the ActionBar
with the embedded SearchView
but does not give any suggestions as it would in the MultiAutoCompleteTextView
.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if (android.os.Build.VERSION.SDK_INT > 10){
inflater.inflate(R.menu.menu11, menu);
searchView = (SearchView) menu.findItem(R.id.MENU_SEARCH).getActionView();
int[] to = {0};
CursorAdapter cursorAdapter = new SimpleCursorAdapter(context, R.layout.listitem, null, allBusStopString, to);
searchView.setSuggestionsAdapter(cursorAdapter);
searchView.setOnSuggestionListener(new OnSuggestionListener() {
@Override
public boolean onSuggestionClick(int position) {
String selectedItem = (String)cursorAdapter.getItem(position);
Log.v("search view", selectedItem);
return false;
}
@Override
public boolean onSuggestionSelect(int position) {
return false;
}
});
}else{
inflater.inflate(R.menu.menu, menu);
}
return true;
}
推荐答案
这很奇怪 SearchView.setSuggestionsAdapter
只接受 CursorAdapter.
That's strange SearchView.setSuggestionsAdapter
accepts CursorAdapter only.
您可以创建 MatrixCursor 并用字符串中的数据填充它大批.我希望你收集的数据很少.
You could create MatrixCursor and fill it with data from String array. I hope you have small data collection.
然后将光标传递给 CursorAdapter.
Then pass the cursor to CursorAdapter.
String[] columnNames = {"_id","text"}
MatrixCursor cursor = new MatrixCursor(columnNames);
String[] array = getResources().getStringArray(R.array.allStrings); //if strings are in resources
String[] temp = new String[2];
int id = 0;
for(String item : array){
temp[0] = Integer.toString(id++);
temp[1] = item;
cursor.addRow(temp);
}
String[] from = {"text"};
int[] to = {R.id.name_entry};
busStopCursorAdapter = new SimpleCursorAdapter(context, R.layout.listentry, cursor, from, to);
这篇关于将 ArrayAdapter 转换为 CursorAdapter 以在 SearchView 中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!