I\'m developing an application where the user presses the \"Search\" icon in the ActionBar
and a SearchView
is made visible at the top of the scree
android:iconifiedByDefault="true"
Above is the code in XML helped me make it expand and autofocus on search view when clicked:
I was having a hard time doing this with SearchView widget
, but the expandActionView() method
is actually defined in the MenuItem class, not SearchView class. So, I solved it by
MenuItem searchItem = menu.findItem(R.id.item_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchItem.expandActionView();
I hope it helps. :)
This worked for me :
In the root layout :
xmlns:app="http://schemas.android.com/apk/res-auto"
SearchView defined as follows :
<android.support.v7.widget.SearchView
android:id="@+id/search_contacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="15dp"
android:background="@drawable/search_view"
app:iconifiedByDefault="false"
app:queryHint="Search name or email"
>
<requestFocus />
</android.support.v7.widget.SearchView>
The difference is with app tag.
app:iconifiedByDefault="false"
app:queryHint="Search name or email"
For Appcompat Searchview you can use this method:
MenuItemCompat.expandActionView(mSearchMenuItem);
@Pascalius's answer worked for me. But every time you close the SearchView, and click again, you lost the Focus. So I inserted the code in a setOnMenuItemClickListener
like this:
MenuItem item = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) item.getActionView();
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
searchView.setIconifiedByDefault(true);
searchView.setFocusable(true);
searchView.setIconified(false);
searchView.requestFocusFromTouch();
return false;
}
});
use this
SearchManager searchManager = (SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = new SearchView(mActivity.actionBar.getThemedContext());
searchView.setSearchableInfo(searchManager.getSearchableInfo(mActivity.getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setQueryHint("Search");
menu.findItem(R.id.action_search).setActionView(searchView);