I am using a search-view element in my fragment to implement search feature.
This can be simply done by setting Iconified to false on OnClick of SearchView.
searchBar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchBar.setIconified(false);
}
});
Reference: Eric Lui's answer
Hopefully it will help.
UPDATE:
You can also use it directly in your XML
app:iconifiedByDefault="false"
For latest versions of android - Try:
app:iconifiedByDefault="false"
Example -
<android.support.v7.widget.SearchView
android:id="@+id/source_location_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:layout_marginRight="20dp"
app:iconifiedByDefault="false"
app:queryHint="Your hint text" />
searchView.setIconified(false);
So recently I've had to do this and I tried all the answers provided but each had some dodgy behaviour - for example the x
close/erase all button would only show up if you'd clicked on the search icon, otherwise you'd be able to edit etc. but you would only see the x
as an erase all button.
Looking at the SearchView
's code I noticed that clicking the mSearchButton
calls onSearchClicked()
and not the suggested onActionViewExpanded()
, but the former is a package private function so it can't be called directly. So I came up with this:
private val searchButton by lazy { searchView.findViewById<ImageView>(R.id.search_button) }
searchView.setOnClickListener { searchButton.callOnClick() }
This way you get the same behaviour no matter where you click and you don't need to manually set the iconified
property in either the xml or programatically.
Use This
searchView.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
searchView.onActionViewExpanded();
OR
searchView.setIconified(false);
}
});
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View view, boolean b)
{
if(!b)
{
if(searchView.getQuery().toString().length() < 1)
{
searchView.setIconified(true); //close the search editor and make search icon again
OR
searchView.onActionViewCollapsed();
}
searchView.clearFocus();
}
}
});
What is the clickable mean? trigger search action or just make the edit area focused? If it is the first, you can just make the icon clickable=false. and make the whole layout clickable and implement a event listener.
<SearchView
android:id="@+id/search_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:click="onClick"
android:layout_marginTop="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginBottom="7dp"
android:background="@color/white" />
The onClick method should be
public void onClick(View v) {
InputMethodManager im = ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE));
im.showSoftInput(editText, 0);
}