Android搜索控件SearchView的用法

When you're ready to add search functionality to your application, Android helps you implement the user interface with either a search dialog that appears at the top of the activity window or a search widget that you can insert in your layout. Both the search dialog and the widget can deliver the user's search query to a specific activity in your application. This way, the user can initiate a search from any activity where the search dialog or widget is available, and the system starts the appropriate activity to perform the search and present results.

Other features available for the search dialog and widget include:

  • Voice search

  • Search suggestions based on recent queries

  • Search suggestions that match actual results in your application data

This guide shows you how to set up your application to provide a search interface that's assisted by the Android system to deliver search queries, using either the search dialog or the search widget.

如果你想给你的app加上搜索的功能,Android可以通过searchview

对于ActionView,我们可以在menu的布局文件使用中来自定义searchview布局,如代码

也可以直接指定Android系统中的SearchView控件,那么这时menu"_search的代码要这样写

大家注意上面的两种方法中一个属性是actionLayout制定一个layout xml布局文件,一个是actionViewClass指定一个类,最终调用可以在Activity中响应onCreateOptionsMenu方法映射这个menu布局即可。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options, menu);
SearchViewsearchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
return super.onCreateOptionsMenu(menu);
}