单击搜索按钮时,在gmail上,操作栏变为白色,并且之前的搜索会有一个下拉列表。
这不是SearchView作为菜单项所获得的。是否有图书馆或类似的东西来实现这一目标?
<item
android:id="@+id/search"
android:orderInCategory="100"
android:title="@string/search_hint"
app:actionViewClass="android.support.v7.widget.SearchView"
android:icon="@drawable/ic_head_search24"
app:showAsAction="always"/>
答案 0 :(得分:2)
您需要关注this教程。
基本上,将其添加到您的菜单中:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/search"
android:title="@string/search_title"
android:icon="@drawable/ic_search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>
然后,创建一个可搜索的配置:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint" />
,在您的活动中:
<activity ... >
...
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable" />
并设置菜单:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
制作将接收搜索结果的活动:
<activity android:name=".SearchResultsActivity" ... >
...
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
...
</activity>
在您的活动中:
public class SearchResultsActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
...
handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
...
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
...
}
答案 1 :(得分:0)
您可以做的另一件事是实现以下内容:
implements SearchView.OnQueryTextListener, SwipeRefreshLayout.OnRefreshListener
在你的活动中。你必须根据界面定义一些方法,但它会带来更强大的体验。
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
@Override
public boolean onQueryTextSubmit(String arg0) {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Create the search view
SearchView searchView = new SearchView(this);
searchView.setQueryHint("Search for Tracks...");
searchView.setOnQueryTextListener(this);
menu.add("Search")
.setIcon(R.drawable.ic_action_search)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return super.onCreateOptionsMenu(menu);
}