to top
Android APIs
public class

SearchView

extends LinearLayout
implements CollapsibleActionView
java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.widget.LinearLayout
         ↳ android.support.v7.widget.SearchView

Class Overview

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

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
Attribute Name Related Method Description
android:iconifiedByDefault setIconifiedByDefault(boolean) The default state of the SearchView. 
android:imeOptions setImeOptions(int) The IME options to set on the query text field. 
android:inputType setInputType(int) The input type to set on the query text field. 
android:maxWidth setMaxWidth(int) An optional maximum width of the SearchView. 
android:queryHint setQueryHint(CharSequence) An optional query hint string to be displayed in the empty query field. 
[Expand]
Inherited XML Attributes
From class android.widget.LinearLayout
From class android.view.ViewGroup
From class android.view.View
[Expand]
Inherited Constants
From class android.widget.LinearLayout
From class android.view.ViewGroup
From class android.view.View
[Expand]
Inherited Fields
From class android.view.View
Public Constructors
SearchView(Context context)
SearchView(Context context, AttributeSet attrs)
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()
Gets the hint text to display 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.
boolean onKeyDown(int keyCode, KeyEvent event)
Handles the key down event for dealing with action keys.
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 onMeasure(int widthMeasureSpec, int heightMeasureSpec)

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

[Expand]
Inherited Methods
From class android.widget.LinearLayout
From class android.view.ViewGroup
From class android.view.View
From class java.lang.Object
From interface android.graphics.drawable.Drawable.Callback
From interface android.support.v7.view.CollapsibleActionView
From interface android.view.KeyEvent.Callback
From interface android.view.ViewManager
From interface android.view.ViewParent
From interface android.view.accessibility.AccessibilityEventSource

XML Attributes

android:iconifiedByDefault

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

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol iconifiedByDefault.

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
normal0x00000000 There are no special semantics associated with this editor.
actionUnspecified0x00000000 There is no specific action associated with this editor, let the editor come up with its own if it can. Corresponds to IME_NULL.
actionNone0x00000001 This editor has no action associated with it. Corresponds to IME_ACTION_NONE.
actionGo0x00000002 The action key performs a "go" operation to take the user to the target of the text they typed. Typically used, for example, when entering a URL. Corresponds to IME_ACTION_GO.
actionSearch0x00000003 The action key performs a "search" operation, taking the user to the results of searching for the text the have typed (in whatever context is appropriate). Corresponds to IME_ACTION_SEARCH.
actionSend0x00000004 The action key performs a "send" operation, delivering the text to its target. This is typically used when composing a message. Corresponds to IME_ACTION_SEND.
actionNext0x00000005 The action key performs a "next" operation, taking the user to the next field that will accept text. Corresponds to IME_ACTION_NEXT.
actionDone0x00000006 The action key performs a "done" operation, closing the soft input method. Corresponds to IME_ACTION_DONE.
actionPrevious0x00000007 The action key performs a "previous" operation, taking the user to the previous field that will accept text. Corresponds to IME_ACTION_PREVIOUS.
flagNoFullscreen0x2000000 Used to request that the IME never go into fullscreen mode. Applications need to be aware that the flag is not a guarantee, and not all IMEs will respect it.

Corresponds to IME_FLAG_NO_FULLSCREEN.

flagNavigatePrevious0x4000000 Like flagNavigateNext, but specifies there is something interesting that a backward navigation can focus on. If the user selects the IME's facility to backward navigate, this will show up in the application as an actionPrevious at InputConnection.performEditorAction(int).

Corresponds to IME_FLAG_NO_FULLSCREEN.

flagNavigateNext0x8000000 Used to specify that there is something interesting that a forward navigation can focus on. This is like using actionNext, except allows the IME to be multiline (with an enter key) as well as provide forward navigation. Note that some IMEs may not be able to do this, especially when running on a small screen where there is little space. In that case it does not need to present a UI for this option. Like actionNext, if the user selects the IME's facility to forward navigate, this will show up in the application at InputConnection.performEditorAction(int).

Corresponds to IME_FLAG_NAVIGATE_NEXT.

flagNoExtractUi0x10000000 Used to specify that the IME does not need to show its extracted text UI. For input methods that may be fullscreen, often when in landscape mode, this allows them to be smaller and let part of the application be shown behind. Though there will likely be limited access to the application available from the user, it can make the experience of a (mostly) fullscreen IME less jarring. Note that when this flag is specified the IME may not be set up to be able to display text, so it should only be used in situations where this is not needed.

Corresponds to IME_FLAG_NO_EXTRACT_UI.

flagNoAccessoryAction0x20000000 Used in conjunction with a custom action, this indicates that the action should not be available as an accessory button when the input method is full-screen. Note that by setting this flag, there can be cases where the action is simply never available to the user. Setting this generally means that you think showing text being edited is more important than the action you have supplied.

Corresponds to IME_FLAG_NO_ACCESSORY_ACTION.

flagNoEnterAction0x40000000 Used in conjunction with a custom action, this indicates that the action should not be available in-line as a replacement for the "enter" key. Typically this is because the action has such a significant impact or is not recoverable enough that accidentally hitting it should be avoided, such as sending a message. Note that TextView will automatically set this flag for you on multi-line text views.

Corresponds to IME_FLAG_NO_ENTER_ACTION.

flagForceAscii0x80000000 Used to request that the IME should be capable of inputting ASCII characters. The intention of this flag is to ensure that the user can type Roman alphabet characters in a TextView used for, typically, account ID or password input. It is expected that IMEs normally are able to input ASCII even without being told so (such IMEs already respect this flag in a sense), but there could be some cases they aren't when, for instance, only non-ASCII input languagaes like Arabic, Greek, Hebrew, Russian are enabled in the IME. Applications need to be aware that the flag is not a guarantee, and not all IMEs will respect it. However, it is strongly recommended for IME authors to respect this flag especially when their IME could end up with a state that has only non-ASCII input languages enabled.

Corresponds to IME_FLAG_FORCE_ASCII.

This corresponds to the global attribute resource symbol imeOptions.

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
none0x00000000 There is no content type. The text is not editable.
text0x00000001 Just plain old text. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_NORMAL.
textCapCharacters0x00001001 Can be combined with text and its variations to request capitalization of all characters. Corresponds to TYPE_TEXT_FLAG_CAP_CHARACTERS.
textCapWords0x00002001 Can be combined with text and its variations to request capitalization of the first character of every word. Corresponds to TYPE_TEXT_FLAG_CAP_WORDS.
textCapSentences0x00004001 Can be combined with text and its variations to request capitalization of the first character of every sentence. Corresponds to TYPE_TEXT_FLAG_CAP_SENTENCES.
textAutoCorrect0x00008001 Can be combined with text and its variations to request auto-correction of text being input. Corresponds to TYPE_TEXT_FLAG_AUTO_CORRECT.
textAutoComplete0x00010001 Can be combined with text and its variations to specify that this field will be doing its own auto-completion and talking with the input method appropriately. Corresponds to TYPE_TEXT_FLAG_AUTO_COMPLETE.
textMultiLine0x00020001 Can be combined with text and its variations to allow multiple lines of text in the field. If this flag is not set, the text field will be constrained to a single line. Corresponds to TYPE_TEXT_FLAG_MULTI_LINE.
textImeMultiLine0x00040001 Can be combined with text and its variations to indicate that though the regular text view should not be multiple lines, the IME should provide multiple lines if it can. Corresponds to TYPE_TEXT_FLAG_IME_MULTI_LINE.
textNoSuggestions0x00080001 Can be combined with text and its variations to indicate that the IME should not show any dictionary-based word suggestions. Corresponds to TYPE_TEXT_FLAG_NO_SUGGESTIONS.
textUri0x00000011 Text that will be used as a URI. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_URI.
textEmailAddress0x00000021 Text that will be used as an e-mail address. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_EMAIL_ADDRESS.
textEmailSubject0x00000031 Text that is being supplied as the subject of an e-mail. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_EMAIL_SUBJECT.
textShortMessage0x00000041 Text that is the content of a short message. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_SHORT_MESSAGE.
textLongMessage0x00000051 Text that is the content of a long message. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_LONG_MESSAGE.
textPersonName0x00000061 Text that is the name of a person. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PERSON_NAME.
textPostalAddress0x00000071 Text that is being supplied as a postal mailing address. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_POSTAL_ADDRESS.
textPassword0x00000081 Text that is a password. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PASSWORD.
textVisiblePassword0x00000091 Text that is a password that should be visible. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_VISIBLE_PASSWORD.
textWebEditText0x000000a1 Text that is being supplied as text in a web form. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_EDIT_TEXT.
textFilter0x000000b1 Text that is filtering some other data. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_FILTER.
textPhonetic0x000000c1 Text that is for phonetic pronunciation, such as a phonetic name field in a contact entry. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PHONETIC.
textWebEmailAddress0x000000d1 Text that will be used as an e-mail address on a web form. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS.
textWebPassword0x000000e1 Text that will be used as a password on a web form. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_PASSWORD.
number0x00000002 A numeric only field. Corresponds to TYPE_CLASS_NUMBER | TYPE_NUMBER_VARIATION_NORMAL.
numberSigned0x00001002 Can be combined with number and its other options to allow a signed number. Corresponds to TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_SIGNED.
numberDecimal0x00002002 Can be combined with number and its other options to allow a decimal (fractional) number. Corresponds to TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_DECIMAL.
numberPassword0x00000012 A numeric password field. Corresponds to TYPE_CLASS_NUMBER | TYPE_NUMBER_VARIATION_PASSWORD.
phone0x00000003 For entering a phone number. Corresponds to TYPE_CLASS_PHONE.
datetime0x00000004 For entering a date and time. Corresponds to TYPE_CLASS_DATETIME | TYPE_DATETIME_VARIATION_NORMAL.
date0x00000014 For entering a date. Corresponds to TYPE_CLASS_DATETIME | TYPE_DATETIME_VARIATION_DATE.
time0x00000024 For entering a time. Corresponds to TYPE_CLASS_DATETIME | TYPE_DATETIME_VARIATION_TIME.

This corresponds to the global attribute resource symbol inputType.

Related Methods

android:maxWidth

An optional maximum width of the SearchView.

Must 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), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol maxWidth.

Related Methods

android:queryHint

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

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

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol queryHint.

Related Methods

Public Constructors

public SearchView (Context context)

public SearchView (Context context, AttributeSet attrs)

Public Methods

public int getImeOptions ()

Returns the IME options set on the query text field.

Related XML Attributes
Returns
  • the ime options

public int getInputType ()

Returns the input type set on the query text field.

Related XML Attributes
Returns
  • the input type

public int getMaxWidth ()

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

Related XML Attributes
Returns
  • the maximum width of the view

public CharSequence getQuery ()

Returns the query string currently in the text field.

Returns
  • the query string

public CharSequence getQueryHint ()

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

Related XML Attributes
Returns
  • the query hint text, if specified, null otherwise.

public CursorAdapter getSuggestionsAdapter ()

Returns the adapter used for suggestions, if any.

Returns
  • the suggestions adapter

public boolean isIconfiedByDefault ()

Returns the default iconified state of the search field.

Related XML Attributes

public boolean isIconified ()

Returns the current iconified state of the SearchView.

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

public boolean isQueryRefinementEnabled ()

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

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

public boolean isSubmitButtonEnabled ()

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

Returns
  • whether the submit button is enabled automatically when necessary

public void onActionViewCollapsed ()

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

public void onActionViewExpanded ()

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

public boolean onKeyDown (int keyCode, KeyEvent event)

Handles the key down event for dealing with action keys.

Parameters
keyCode This is the keycode of the typed key, and is the same value as found in the KeyEvent parameter.
event The complete event record for the typed key
Returns
  • true if the event was handled here, or false if not.

public 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 True if the window containing this view now has focus, false otherwise.

public 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 a true value will collapse the SearchView to an icon, while a false will expand it.

public 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 whether the search field should be iconified by default

public void setImeOptions (int imeOptions)

Sets the IME options on the query text field.

Related XML Attributes
Parameters
imeOptions the options to set on the query text field

public void setInputType (int inputType)

Sets the input type on the query text field.

Related XML Attributes
Parameters
inputType the input type to set on the query text field

public void setMaxWidth (int maxpixels)

Makes the view at most this many pixels wide

Related XML Attributes

public void setOnCloseListener (SearchView.OnCloseListener listener)

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

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

public void setOnQueryTextFocusChangeListener (View.OnFocusChangeListener listener)

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

Parameters
listener the listener to inform of focus changes.

public void setOnQueryTextListener (SearchView.OnQueryTextListener listener)

Sets a listener for user actions within the SearchView.

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

public 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 the listener to inform when the search button is clicked or the text field is programmatically de-iconified.

public void setOnSuggestionListener (SearchView.OnSuggestionListener listener)

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

Parameters
listener the listener to inform of suggestion selection events.

public void setQuery (CharSequence query, boolean submit)

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

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

public void setQueryHint (CharSequence hint)

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

Related XML Attributes
Parameters
hint the hint text to display

public 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 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.

public 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 a SearchableInfo can be retrieved from the SearchManager, for a specific activity or a global search provider.

public 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 true to show a submit button for submitting queries, false if a submit button is not required.

public 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.

Protected Methods

protected void onDetachedFromWindow ()

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

protected 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 overriden 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 horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.