我想出了一个解决方案,可以在横向中完全扩展搜索视图,并且在创建活动时也已经扩展了操作视图。它是如何工作的:
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>
Note: "@string/search" - looks something like this in the res-strings.xml:
<string name="search">Search</string>
2.Second create the layout referred above ("@layout/searchview_layout") in res-layout folder. The new layout: searchview_layout.xml will look like this:
<?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"/>
Note: Here we are setting the search view width to match the width of its parent( android:layout_width="match_parent")
3.In your MainActivity class or in the activity that has to implement the Search View write in the onCreateOptionsMenu() method the following code:
@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;
}