我是android开发新手.我想要的是使用动作栏搜索视图小部件搜索我的列表视图.我该如何实现搜索功能.我缺少的是搜索功能.我看过一些搜索功能,但它基于editText.请帮忙.
这是我的代码:
menu.xml文件
在我的manifest.xml中
在我的MainActivity.java上
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.lv = (ListView) findViewById(R.id.listView);
this.databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
this.persons= getPersonList();
Adapter adapter = new Adapter(this,persons);
this.lv.setAdapter(adapter);
}
public List
最佳答案
您需要在适配器中实现Filterable接口.
然后膨胀菜单:
@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
if (searchMenuItem == null) {
return;
}
searchView = (SearchView) searchMenuItem.getActionView();
if (searchView != null) {
searchView.setQueryHint(getString(R.string.search_hint));
searchView.setMaxWidth(2129960); // https://stackoverflow.com/questions/18063103/searchview-in-optionsmenu-not-full-width
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
SearchFragment.this.onQueryTextChange(s);
return false;
}
});
}
}
void onQueryTextChange(String query) {
searchAdapter.getFilter().filter(query);
}
查找更多信息here