我刚刚在操作栏中实现了“ android.support.v7.widget.SearchView ”来搜索一些pdf文件。 当我为搜索插入多个字符时,会完整地显示建议列表。但是当我只输入一个单个字符时,没有显示任何提议,尽管调用填充建议的功能被调用。 您是否知道如何更改该行为,以便在仅输入一个字符时显示提案?
这是我在菜单中定义搜索视图的地方。
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/pdf_menu_search_item"
android:icon="@mipmap/ic_search_white_24dp"
android:title="Suche"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"/></menu>
在我的活动中,实现了以下代码:
private static final String[] SUGGESTIONS = {
"Amsterdam","Berlin","Rome"
};
private SimpleCursorAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contextual_actionbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
final SearchView mSearchView;
mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.pdf_menu_search_item));
final String[] from = new String[] {"cityName"};
final int[] to = new int[] {android.R.id.text1};
mAdapter = new SimpleCursorAdapter(Startseite.this,
android.R.layout.simple_list_item_1,
null,
from,
to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
mSearchView.setSuggestionsAdapter(mAdapter);
mSearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionClick(int position) {
return true;
}
@Override
public boolean onSuggestionSelect(int position) {
return true;
}
});
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
populateAdapter(newText);
return true;
}
});
return super.onPrepareOptionsMenu(menu);
}
// You must implements your logic to get data using OrmLite
private void populateAdapter(String query) {
final MatrixCursor c = new MatrixCursor(new String[]{ BaseColumns._ID, "cityName" });
for (int i=0; i<SUGGESTIONS.length; i++) {
if (SUGGESTIONS[i].toLowerCase().startsWith(query.toLowerCase()))
{ c.addRow(new Object[] {i, SUGGESTIONS[i]}); }
}
mAdapter.changeCursor(c);
mAdapter.notifyDataSetChanged();
}
请有人知道如何解决这个问题吗?
答案 0 :(得分:2)
我刚刚找到答案。 如果您正在使用AppCompatActivity(像我一样),您可以设置searchview阈值:
AutoCompleteTextView searchAutoCompleteTextView = (AutoCompleteTextView) mSearchView.findViewById(getResources().getIdentifier("search_src_text", "id", getPackageName()));
searchAutoCompleteTextView.setThreshold(1);
现在搜索建议将从第一个字符开始显示。 也许这对其他人有帮助:))