Most visited

Recently visited

SearchView

public class SearchView
extends LinearLayoutCompat implements CollapsibleActionView

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.support.v7.widget.LinearLayoutCompat
         ↳ android.support.v7.widget.SearchView


A widget that provides a user interface for the user to enter a search query and submit a request to a search provider. Shows a list of query suggestions or results, if available, and allows the user to pick a suggestion or result to launch into.

Note: This class is included in the support library for compatibility with API level 7 and higher. If you're developing your app for API level 11 and higher only, you should instead use the framework SearchView class.

When the SearchView is used in an ActionBar as an action view, it's collapsed by default, so you must provide an icon for the action.

If you want the search field to always be visible, then call setIconifiedByDefault(false).

Developer Guides

For information about using SearchView, read the Search API guide. Additional information about action views is also available in the <Action Bar API guide

See also:

Summary

Nested classes

interface SearchView.OnCloseListener

 

interface SearchView.OnQueryTextListener

Callbacks for changes to the query text. 

interface SearchView.OnSuggestionListener

Callback interface for selection events on suggestions. 

XML attributes

android.support.v7.appcompat:iconifiedByDefault The default state of the SearchView. 
android.support.v7.appcompat:queryHint An optional user-defined query hint string to be displayed in the empty query field. 
android:imeOptions The IME options to set on the query text field. 
android:inputType The input type to set on the query text field. 
android:maxWidth An optional maximum width of the SearchView. 

Inherited XML attributes

From class android.view.ViewGroup
From class android.view.View

Inherited constants

From class android.support.v7.widget.LinearLayoutCompat
From class android.view.ViewGroup
From class android.view.View

Inherited fields

From class android.view.View

Public constructors

SearchView(Context context)
SearchView(Context context, AttributeSet attrs)
SearchView(Context context, AttributeSet attrs, int defStyleAttr)

Public methods

int getImeOptions()

Returns the IME options set on the query text field.

int getInputType()

Returns the input type set on the query text field.

int getMaxWidth()

Gets the specified maximum width in pixels, if set.

CharSequence getQuery()

Returns the query string currently in the text field.

CharSequence getQueryHint()

Returns the hint text that will be displayed in the query text field.

CursorAdapter getSuggestionsAdapter()

Returns the adapter used for suggestions, if any.

boolean isIconfiedByDefault()

Returns the default iconified state of the search field.

boolean isIconified()

Returns the current iconified state of the SearchView.

boolean isQueryRefinementEnabled()

Returns whether query refinement is enabled for all items or only specific ones.

boolean isSubmitButtonEnabled()

Returns whether the submit button is enabled when necessary or never displayed.

void onActionViewCollapsed()

Called when this view is collapsed as an action view.

void onActionViewExpanded()

Called when this view is expanded as an action view.

void onWindowFocusChanged(boolean hasWindowFocus)

Called when the window containing this view gains or loses focus.

void setIconified(boolean iconify)

Iconifies or expands the SearchView.

void setIconifiedByDefault(boolean iconified)

Sets the default or resting state of the search field.

void setImeOptions(int imeOptions)

Sets the IME options on the query text field.

void setInputType(int inputType)

Sets the input type on the query text field.

void setMaxWidth(int maxpixels)

Makes the view at most this many pixels wide

void setOnCloseListener(SearchView.OnCloseListener listener)

Sets a listener to inform when the user closes the SearchView.

void setOnQueryTextFocusChangeListener(View.OnFocusChangeListener listener)

Sets a listener to inform when the focus of the query text field changes.

void setOnQueryTextListener(SearchView.OnQueryTextListener listener)

Sets a listener for user actions within the SearchView.

void setOnSearchClickListener(View.OnClickListener listener)

Sets a listener to inform when the search button is pressed.

void setOnSuggestionListener(SearchView.OnSuggestionListener listener)

Sets a listener to inform when a suggestion is focused or clicked.

void setQuery(CharSequence query, boolean submit)

Sets a query string in the text field and optionally submits the query as well.

void setQueryHint(CharSequence hint)

Sets the hint text to display in the query text field.

void setQueryRefinementEnabled(boolean enable)

Specifies if a query refinement button should be displayed alongside each suggestion or if it should depend on the flags set in the individual items retrieved from the suggestions provider.

void setSearchableInfo(SearchableInfo searchable)

Sets the SearchableInfo for this SearchView.

void setSubmitButtonEnabled(boolean enabled)

Enables showing a submit button when the query is non-empty.

void setSuggestionsAdapter(CursorAdapter adapter)

You can set a custom adapter if you wish.

Protected methods

void onDetachedFromWindow()

This is called when the view is detached from a window.

void onLayout(boolean changed, int left, int top, int right, int bottom)

Called from layout when this view should assign a size and position to each of its children.

void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

void onRestoreInstanceState(Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState().

Parcelable onSaveInstanceState()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state.

Inherited methods

From class android.support.v7.widget.LinearLayoutCompat
From class android.view.ViewGroup
From class android.view.View
From class java.lang.Object
From interface android.view.ViewParent
From interface android.view.ViewManager
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.accessibility.AccessibilityEventSource
From interface android.support.v7.view.CollapsibleActionView

XML attributes

android.support.v7.appcompat:iconifiedByDefault

The default state of the SearchView. If true, it will be iconified when not in use and expanded when clicked.

May be a boolean value, such as "true" or "false".

Related methods:

android.support.v7.appcompat:queryHint

An optional user-defined query hint string to be displayed in the empty query field.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

android:imeOptions

The IME options to set on the query text field.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
normal0
actionDone6
actionGo2
actionNext5
actionNone1
actionPrevious7
actionSearch3
actionSend4
actionUnspecified0
flagForceAscii80000000
flagNavigateNext8000000
flagNavigatePrevious4000000
flagNoAccessoryAction20000000
flagNoEnterAction40000000
flagNoExtractUi10000000
flagNoFullscreen2000000

Related methods:

android:inputType

The input type to set on the query text field.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
none0
date14
datetime4
number2
numberDecimal2002
numberPassword12
numberSigned1002
phone3
text1
textAutoComplete10001
textAutoCorrect8001
textCapCharacters1001
textCapSentences4001
textCapWords2001
textEmailAddress21
textEmailSubject31
textFilterb1
textImeMultiLine40001
textLongMessage51
textMultiLine20001
textNoSuggestions80001
textPassword81
textPersonName61
textPhoneticc1
textPostalAddress71
textShortMessage41
textUri11
textVisiblePassword91
textWebEditTexta1
textWebEmailAddressd1
textWebPassworde1
time24

Related methods:

android:maxWidth

An optional maximum width of the SearchView.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

Public constructors

SearchView

SearchView (Context context)

Parameters
context Context

SearchView

SearchView (Context context, 
                AttributeSet attrs)

Parameters
context Context
attrs AttributeSet

SearchView

SearchView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr)

Parameters
context Context
attrs AttributeSet
defStyleAttr int

Public methods

getImeOptions

int getImeOptions ()

Returns the IME options set on the query text field.

Related XML Attributes:

Returns
int the ime options

See also:

getInputType

int getInputType ()

Returns the input type set on the query text field.

Related XML Attributes:

Returns
int the input type

getMaxWidth

int getMaxWidth ()

Gets the specified maximum width in pixels, if set. Returns zero if no maximum width was specified.

Related XML Attributes:

Returns
int the maximum width of the view

getQuery

CharSequence getQuery ()

Returns the query string currently in the text field.

Returns
CharSequence the query string

getQueryHint

CharSequence getQueryHint ()

Returns the hint text that will be displayed in the query text field.

The displayed query hint is chosen in the following order:

  1. Non-null value set with setQueryHint(CharSequence)
  2. Value specified in XML using app:queryHint
  3. Valid string resource ID exposed by the SearchableInfo via getHintId()
  4. Default hint provided by the theme against which the view was inflated

Related XML Attributes:

Returns
CharSequence the displayed query hint text, or null if none set

getSuggestionsAdapter

CursorAdapter getSuggestionsAdapter ()

Returns the adapter used for suggestions, if any.

Returns
CursorAdapter the suggestions adapter

isIconfiedByDefault

boolean isIconfiedByDefault ()

Returns the default iconified state of the search field.

Related XML Attributes:

Returns
boolean

isIconified

boolean isIconified ()

Returns the current iconified state of the SearchView.

Returns
boolean true if the SearchView is currently iconified, false if the search field is fully visible.

isQueryRefinementEnabled

boolean isQueryRefinementEnabled ()

Returns whether query refinement is enabled for all items or only specific ones.

Returns
boolean true if enabled for all items, false otherwise.

isSubmitButtonEnabled

boolean isSubmitButtonEnabled ()

Returns whether the submit button is enabled when necessary or never displayed.

Returns
boolean whether the submit button is enabled automatically when necessary

onActionViewCollapsed

void onActionViewCollapsed ()

Called when this view is collapsed as an action view. See collapseActionView(android.view.MenuItem).

onActionViewExpanded

void onActionViewExpanded ()

Called when this view is expanded as an action view. See expandActionView(android.view.MenuItem).

onWindowFocusChanged

void onWindowFocusChanged (boolean hasWindowFocus)

Called when the window containing this view gains or loses focus. Note that this is separate from view focus: to receive key events, both your view and its window must have focus. If a window is displayed on top of yours that takes input focus, then your own window will lose focus but the view focus will remain unchanged.

Parameters
hasWindowFocus boolean: True if the window containing this view now has focus, false otherwise.

setIconified

void setIconified (boolean iconify)

Iconifies or expands the SearchView. Any query text is cleared when iconified. This is a temporary state and does not override the default iconified state set by setIconifiedByDefault(boolean). If the default state is iconified, then a false here will only be valid until the user closes the field. And if the default state is expanded, then a true here will only clear the text field and not close it.

Parameters
iconify boolean: a true value will collapse the SearchView to an icon, while a false will expand it.

setIconifiedByDefault

void setIconifiedByDefault (boolean iconified)

Sets the default or resting state of the search field. If true, a single search icon is shown by default and expands to show the text field and other buttons when pressed. Also, if the default state is iconified, then it collapses to that state when the close button is pressed. Changes to this property will take effect immediately.

The default value is true.

Related XML Attributes:

Parameters
iconified boolean: whether the search field should be iconified by default

setImeOptions

void setImeOptions (int imeOptions)

Sets the IME options on the query text field.

Related XML Attributes:

Parameters
imeOptions int: the options to set on the query text field

See also:

setInputType

void setInputType (int inputType)

Sets the input type on the query text field.

Related XML Attributes:

Parameters
inputType int: the input type to set on the query text field

See also:

setMaxWidth

void setMaxWidth (int maxpixels)

Makes the view at most this many pixels wide

Related XML Attributes:

Parameters
maxpixels int

setOnCloseListener

void setOnCloseListener (SearchView.OnCloseListener listener)

Sets a listener to inform when the user closes the SearchView.

Parameters
listener SearchView.OnCloseListener: the listener to call when the user closes the SearchView.

setOnQueryTextFocusChangeListener

void setOnQueryTextFocusChangeListener (View.OnFocusChangeListener listener)

Sets a listener to inform when the focus of the query text field changes.

Parameters
listener View.OnFocusChangeListener: the listener to inform of focus changes.

setOnQueryTextListener

void setOnQueryTextListener (SearchView.OnQueryTextListener listener)

Sets a listener for user actions within the SearchView.

Parameters
listener SearchView.OnQueryTextListener: the listener object that receives callbacks when the user performs actions in the SearchView such as clicking on buttons or typing a query.

setOnSearchClickListener

void setOnSearchClickListener (View.OnClickListener listener)

Sets a listener to inform when the search button is pressed. This is only relevant when the text field is not visible by default. Calling setIconified(false) can also cause this listener to be informed.

Parameters
listener View.OnClickListener: the listener to inform when the search button is clicked or the text field is programmatically de-iconified.

setOnSuggestionListener

void setOnSuggestionListener (SearchView.OnSuggestionListener listener)

Sets a listener to inform when a suggestion is focused or clicked.

Parameters
listener SearchView.OnSuggestionListener: the listener to inform of suggestion selection events.

setQuery

void setQuery (CharSequence query, 
                boolean submit)

Sets a query string in the text field and optionally submits the query as well.

Parameters
query CharSequence: the query string. This replaces any query text already present in the text field.
submit boolean: whether to submit the query right now or only update the contents of text field.

setQueryHint

void setQueryHint (CharSequence hint)

Sets the hint text to display in the query text field. This overrides any hint specified in the SearchableInfo.

This value may be specified as an empty string to prevent any query hint from being displayed.

Related XML Attributes:

Parameters
hint CharSequence: the hint text to display or null to clear

setQueryRefinementEnabled

void setQueryRefinementEnabled (boolean enable)

Specifies if a query refinement button should be displayed alongside each suggestion or if it should depend on the flags set in the individual items retrieved from the suggestions provider. Clicking on the query refinement button will replace the text in the query text field with the text from the suggestion. This flag only takes effect if a SearchableInfo has been specified with setSearchableInfo(SearchableInfo) and not when using a custom adapter.

Parameters
enable boolean: true if all items should have a query refinement button, false if only those items that have a query refinement flag set should have the button.

See also:

setSearchableInfo

void setSearchableInfo (SearchableInfo searchable)

Sets the SearchableInfo for this SearchView. Properties in the SearchableInfo are used to display labels, hints, suggestions, create intents for launching search results screens and controlling other affordances such as a voice button.

Parameters
searchable SearchableInfo: a SearchableInfo can be retrieved from the SearchManager, for a specific activity or a global search provider.

setSubmitButtonEnabled

void setSubmitButtonEnabled (boolean enabled)

Enables showing a submit button when the query is non-empty. In cases where the SearchView is being used to filter the contents of the current activity and doesn't launch a separate results activity, then the submit button should be disabled.

Parameters
enabled boolean: true to show a submit button for submitting queries, false if a submit button is not required.

setSuggestionsAdapter

void setSuggestionsAdapter (CursorAdapter adapter)

You can set a custom adapter if you wish. Otherwise the default adapter is used to display the suggestions from the suggestions provider associated with the SearchableInfo.

Parameters
adapter CursorAdapter

See also:

Protected methods

onDetachedFromWindow

void onDetachedFromWindow ()

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.

onLayout

void onLayout (boolean changed, 
                int left, 
                int top, 
                int right, 
                int bottom)

Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.

Parameters
changed boolean: This is a new size or position for this view
left int: Left position, relative to parent
top int: Top position, relative to parent
right int: Right position, relative to parent
bottom int: Bottom position, relative to parent

onMeasure

void onMeasure (int widthMeasureSpec, 
                int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overridden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpec int: horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec int: vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

onRestoreInstanceState

void onRestoreInstanceState (Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState(). This function will never be called with a null state.

Parameters
state Parcelable: The frozen state that had previously been returned by onSaveInstanceState().

onSaveInstanceState

Parcelable onSaveInstanceState ()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

Some examples of things you may store here: the current cursor position in a text view (but usually not the text itself since that is stored in a content provider or other persistent storage), the currently selected item in a list view.

Returns
Parcelable Returns a Parcelable object containing the view's current dynamic state, or null if there is nothing interesting to save. The default implementation returns null.

Hooray!