我想出了一个解决方案,可以在横向中完全扩展搜索视图,并且在创建活动时也已经扩展了操作视图。它是如何工作的:
1.首先在您的 res-menu 文件夹中创建一个 xml 文件,例如:searchview_in_menu.xml。在这里,您将拥有以下代码:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/action_search"
android:title="@string/search"
android:icon="@android:drawable/ic_menu_search"
android:actionLayout="@layout/searchview_layout" />
</menu>
注意:“@string/search” - 在 res-strings.xml 中看起来像这样:
<string name="search">Search</string>
2.第二次在 res-layout 文件夹中创建上述布局(“@layout/searchview_layout”)。新布局:searchview_layout.xml 将如下所示:
<?xml version="1.0" encoding="utf-8"?>
<SearchView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/search_view_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
注意:这里我们将搜索视图的宽度设置为匹配其父级的宽度(android:layout_width="match_parent")
3.在您的 MainActivity 类或必须实现 Search View 的活动中,在 onCreateOptionsMenu() 方法中写入以下代码:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.searchview_in_menu, menu);
//find the search view item and inflate it in the menu layout
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchItem.getActionView();
//set a hint on the search view (optional)
mSearchView.setQueryHint(getString(R.string.search));
//these flags together with the search view layout expand the search view in the landscape mode
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
| MenuItem.SHOW_AS_ACTION_ALWAYS);
//expand the search view when entering the activity(optional)
searchItem.expandActionView();
return true;
}