Home | History | Annotate | Download | only in search
      1 page.title=Creating a Search Interface
      2 parent.title=Search
      3 parent.link=index.html
      4 @jd:body
      5 
      6 <div id="qv-wrapper">
      7 <div id="qv">
      8 
      9   <h2>Quickview</h2>
     10   <ul>
     11     <li>The Android system sends search queries from the search dialog or widget to an activity you
     12 specify to perform searches and present results</li>
     13     <li>You can put the search widget in the Action Bar, as an "action view," for quick
     14 access</li>
     15   </ul>
     16 
     17 
     18 <h2>In this document</h2>
     19 <ol>
     20   <li><a href="#TheBasics">The Basics</a></li>
     21   <li><a href="#SearchableConfiguration">Creating a Searchable Configuration</a></li>
     22   <li><a href="#SearchableActivity">Creating a Searchable Activity</a>
     23     <ol>
     24       <li><a href="#DeclaringSearchableActivity">Declaring a searchable activity</a></li>
     25       <li><a href="#PerformingSearch">Performing a search</a></li>
     26     </ol>
     27   </li>
     28   <li><a href="#SearchDialog">Using the Search Dialog</a>
     29     <ol>
     30       <li><a href="#InvokingTheSearchDialog">Invoking the search dialog</a></li>
     31       <li><a href="#LifeCycle">The impact of the search dialog on your activity lifecycle</a></li>
     32       <li><a href="#SearchContextData">Passing search context data</a></li>
     33     </ol>
     34   </li>
     35   <li><a href="#UsingSearchWidget">Using the Search Widget</a>
     36     <ol>
     37       <li><a href="#ConfiguringWidget">Configuring the search widget</a></li>
     38       <li><a href="#WidgetFeatures">Other search widget features</a></li>
     39       <li><a href="#UsingBoth">Using both the widget and the dialog</a></li>
     40     </ol>
     41   </li>
     42   <li><a href="#VoiceSearch">Adding Voice Search</a></li>
     43   <li><a href="#SearchSuggestions">Adding Search Suggestions</a></li>
     44 </ol>
     45 
     46 <h2>Key classes</h2>
     47 <ol>
     48 <li>{@link android.app.SearchManager}</li>
     49 <li>{@link android.widget.SearchView}</li>
     50 </ol>
     51 
     52 <h2>Related samples</h2>
     53 <ol>
     54 <li><a href="{@docRoot}resources/samples/SearchableDictionary/index.html">Searchable
     55 Dictionary</a></li>
     56 <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/SearchViewActionBar.html">SearchView
     57     in the Action Bar</a></li>
     58 <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/SearchViewFilterMode.html">SearchView
     59     filter mode</a></li>
     60 </ol>
     61 
     62 <h2>Downloads</h2>
     63 <ol>
     64 <li><a href="{@docRoot}shareables/search_icons.zip">search_icons.zip</a></li>
     65 </ol>
     66 
     67 <h2>See also</h2>
     68 <ol>
     69 <li><a href="adding-recent-query-suggestions.html">Adding Recent Query Suggestions</a></li>
     70 <li><a href="adding-custom-suggestions.html">Adding Custom Suggestions</a></li>
     71 <li><a href="searchable-config.html">Searchable Configuration</a></li>
     72 </ol>
     73 
     74 </div>
     75 </div>
     76 
     77 <p>When you're ready to add search functionality to your application, Android helps you implement
     78 the user interface with either a search dialog that appears at the top of the activity window or a
     79 search widget that you can insert in your layout. Both the search dialog and the widget can deliver
     80 the user's search query to a specific activity in your application. This way, the user can initiate
     81 a search from any activity where the search dialog or widget is available, and the system starts the
     82 appropriate activity to perform the search and present results.</p>
     83 
     84 <p>Other features available for the search dialog and widget include:</p>
     85 
     86 <ul>
     87   <li>Voice search</li>
     88   <li>Search suggestions based on recent queries</li>
     89   <li>Search suggestions that match actual results in your application data</li>
     90 </ul>
     91 
     92 <p>This guide shows you how to set up your application to provide a search interface
     93 that's assisted by the Android system to deliver search queries, using either the
     94 search dialog or the search widget.</p>
     95 
     96 
     97 <h2 id="TheBasics">The Basics</h2>
     98 
     99 <div class="figure" style="width:250px">
    100 <img src="{@docRoot}images/search/search-ui.png" alt="" height="417" />
    101 <p class="img-caption"><strong>Figure 1.</strong> Screenshot of an application's search dialog.</p>
    102 </div>
    103 
    104 <p>Before you begin, you should decide whether you'll implement your search interface using the
    105 search dialog or the search widget. Both provide the same search features, but in slightly different
    106 ways:</p>
    107 
    108 <ul>
    109   <li>The <strong>search dialog</strong> is a UI component that's controlled by the Android system.
    110 When activated by the user, the search dialog appears at the top of the activity, as shown in figure
    111 1.
    112     <p>The Android system controls all events in the search dialog. When the user
    113 submits a query, the system delivers the query to the activity that you specify to
    114 handle searches. The dialog can also provide search suggestions while the user types.</p></li>
    115 
    116   <li>The <strong>search widget</strong> is an instance of {@link android.widget.SearchView} that
    117 you can place anywhere in your layout. By default, the search widget behaves like a standard {@link
    118 android.widget.EditText} widget and doesn't do anything, but you can configure it so that the
    119 Android system handles all input events, delivers queries to the appropriate activity, and provides
    120 search suggestions (just like the search dialog). However, the search widget is available only in
    121 Android 3.0 (API Level 11) and higher.
    122 
    123 <p class="note"><strong>Note:</strong> If you want, you can handle all user input into the
    124 search widget yourself, using various callback methods and listeners. This document, however,
    125 focuses on how to integrate the search widget with the system for an assisted search
    126 implementation. If you want to handle all user input yourself, read the reference documentation for
    127 {@link android.widget.SearchView} and its nested interfaces. </p></li>
    128 </ul>
    129 
    130 <p>When the user executes a search from the search dialog or a search widget, the system creates an
    131 {@link android.content.Intent} and stores the user query in it. The system then starts the activity
    132 that you've declared to handle searches (the "searchable activity") and delivers it the intent. To
    133 set up your application for this kind of assisted search, you need the following:</p>
    134 
    135 <ul>
    136   <li>A searchable configuration
    137   <p>An XML file that configures some settings for the search dialog or widget. It includes settings
    138 for features such as voice search, search suggestion, and hint text for the search box.</p></li>
    139   <li>A searchable activity
    140   <p>The {@link android.app.Activity} that receives the search query, searches your
    141 data, and displays the search results.</p></li>
    142   <li>A search interface, provided by either:
    143     <ul>
    144       <li>The search dialog
    145         <p>By default, the search dialog is hidden, but appears at the top of the screen when the 
    146 user presses the device SEARCH button (when available) or another button in your user interface.</p>
    147       </li>
    148       <li>Or, a {@link android.widget.SearchView} widget
    149         <p>Using the search widget allows you to put the search box anywhere in your activity.
    150 Instead of putting it in your activity layout, however, it's usually more convenient for users as an
    151 <a href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">action view in the Action Bar</a>.</p>
    152       </li>
    153     </ul>
    154   </li>
    155 </ul>
    156 
    157 <p>The rest of this document shows you how to create the searchable configuration, searchable
    158 activity, and implement a search interface with either the search dialog or search widget.</p>
    159 
    160 
    161 <h2 id="SearchableConfiguration">Creating a Searchable Configuration</h2>
    162 
    163 <p>The first thing you need is an XML file called the searchable configuration. It configures
    164 certain UI aspects of the search dialog or widget and defines how features such as suggestions and
    165 voice search behave. This file is traditionally named {@code searchable.xml} and must be saved in
    166 the {@code res/xml/} project directory.</p>
    167 
    168 <p class="note"><strong>Note:</strong> The system uses this file to instantiate a {@link
    169 android.app.SearchableInfo} object, but you cannot create this object yourself at
    170 runtime&mdash;you must declare the searchable configuration in XML.</p>
    171 
    172 <p>The searchable configuration file must include the <a
    173 href="{@docRoot}guide/topics/search/searchable-config.html#searchable-element">{@code
    174 &lt;searchable&gt;}</a> element as the root node and specify one
    175 or more attributes. For example:</p>
    176 
    177 <pre>
    178 &lt;?xml version="1.0" encoding="utf-8"?>
    179 &lt;searchable xmlns:android="http://schemas.android.com/apk/res/android"
    180     android:label="@string/app_label"
    181     android:hint="@string/search_hint" >
    182 &lt;/searchable>
    183 </pre>
    184 
    185 <p>The {@code android:label} attribute is the only required attribute. It points to a string
    186 resource, which should be the application name. This label isn't actually visible to the
    187 user until you enable search suggestions for Quick Search Box. At that point, this label is visible
    188 in the list of Searchable items in the system Settings.</p>
    189 
    190 <p>Though it's not required, we recommend that you always include the {@code android:hint}
    191 attribute, which provides a hint string in the search box before users
    192 enters a query. The hint is important because it provides important clues to users about what
    193 they can search.</p>
    194 
    195 <p class="note"><strong>Tip:</strong> For consistency among other
    196 Android applications, you should format the string for {@code android:hint} as "Search
    197 &lt;content-or-product&gt;". For example, "Search songs and artists" or "Search
    198 YouTube".</p>
    199 
    200 <p>The <a
    201 href="{@docRoot}guide/topics/search/searchable-config.html#searchable-element">{@code
    202 &lt;searchable&gt;}</a> element accepts several other attributes. However, you don't need
    203 most attributes until you add features such as <a href="#SearchSuggestions">search suggestions</a>
    204 and <a href="#VoiceSearch">voice search</a>. For detailed information about the searchable
    205 configuration file, see the <a
    206 href="{@docRoot}guide/topics/search/searchable-config.html">Searchable Configuration</a> reference
    207 document.</p>
    208 
    209 
    210 
    211 <h2 id="SearchableActivity">Creating a Searchable Activity</h2>
    212 
    213 <p>A searchable activity is the {@link android.app.Activity} in your application that performs
    214 searches based on a query string and presents the search results.</p>
    215 
    216 <p>When the user executes a search in the search dialog or widget, the system starts your
    217 searchable activity and delivers it the search query in an {@link
    218 android.content.Intent} with the  {@link android.content.Intent#ACTION_SEARCH} action. Your
    219 searchable activity retrieves the query from the intent's {@link android.app.SearchManager#QUERY
    220 QUERY} extra, then searches your data and presents the results.</p>
    221 
    222 <p>Because you may include the search dialog or widget in any other activity in your application,
    223 the system must know which activity is your searchable activity, so it can properly deliver the
    224 search query. So, you must first declare your searchable activity in the Android manifest file.</p>
    225 
    226 
    227 <h3 id="DeclaringSearchableActivity">Declaring a searchable activity</h3>
    228 
    229 <p>If you don't have one already, create an {@link android.app.Activity} that will perform
    230 searches and present results. You don't need to implement the search functionality yet&mdash;just
    231 create an activity that you can declare in the manifest. Inside the manifest's <a
    232 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a>
    233 element:</p>
    234 <ol>
    235   <li>Declare the activity to accept the {@link android.content.Intent#ACTION_SEARCH} intent, in an
    236 <a href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code
    237 &lt;intent-filter&gt;}</a>
    238 element.</li>
    239   <li>Specify the searchable configuration to use, in a <a
    240 href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code &lt;meta-data&gt;}</a>
    241 element.</li>
    242 </ol>
    243 
    244 <p>For example:</p>
    245 
    246 <pre>
    247 &lt;application ... >
    248     &lt;activity android:name=".SearchableActivity" >
    249         &lt;intent-filter>
    250             &lt;action android:name="android.intent.action.SEARCH" />
    251         &lt;/intent-filter>
    252         &lt;meta-data android:name="android.app.searchable"
    253                    android:resource="@xml/searchable"/>
    254     &lt;/activity>
    255     ...
    256 &lt;/application>
    257 </pre>
    258 
    259 <p>The {@code &lt;meta-data&gt;} element must include the {@code android:name} attribute with a
    260 value of {@code "android.app.searchable"} and the {@code android:resource} attribute with a
    261 reference to the searchable configuration file (in this example, it
    262 refers to the {@code res/xml/searchable.xml} file).</p>
    263 
    264 <p class="note"><strong>Note:</strong> The <a
    265 href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code
    266 &lt;intent-filter&gt;}</a> does not need a <a
    267 href="{@docRoot}guide/topics/manifest/category-element.html">{@code &lt;category&gt;}</a> with the
    268 {@code DEFAULT} value (which you usually see in <a
    269 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a> elements),
    270 because the system delivers the {@link android.content.Intent#ACTION_SEARCH} intent explicitly to
    271 your searchable activity, using its component name.</p>
    272 
    273 
    274 
    275 <h3 id="PerformingSearch">Performing a search</h3>
    276 
    277 <p>Once you have declared your searchable activity in the manifest, performing a search in your
    278 searchable activity involves three steps:</p>
    279 
    280 <ol>
    281   <li><a href="#ReceivingTheQuery">Receiving the query</a></li>
    282   <li><a href="#SearchingYourData">Searching your data</a></li>
    283   <li><a href="#PresentingTheResults">Presenting the results</a></li>
    284 </ol>
    285 
    286 <p>Traditionally, your search results should be presented in a {@link android.widget.ListView}, so
    287 you might want your searchable activity to extend {@link android.app.ListActivity}. It includes
    288 a default layout with a single {@link android.widget.ListView} and provides several
    289 convenience methods for working with the {@link android.widget.ListView}.</p>
    290 
    291 
    292 <h4 id="ReceivingTheQuery">Receiving the query</h4>
    293 
    294 <p>When a user executes a search from the search dialog or widget, the system starts your
    295 searchable activity and sends it a {@link android.content.Intent#ACTION_SEARCH} intent. This intent
    296 carries the search query in the
    297 {@link android.app.SearchManager#QUERY QUERY} string extra. You must check for
    298 this intent when the activity starts and extract the string. For example, here's how you can get the
    299 search query when your searchable activity starts:</p>
    300 
    301 <pre>
    302 &#64;Override
    303 public void onCreate(Bundle savedInstanceState) {
    304     super.onCreate(savedInstanceState);
    305     setContentView(R.layout.search);
    306 
    307     // Get the intent, verify the action and get the query
    308     Intent intent = getIntent();
    309     if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
    310       String query = intent.getStringExtra(SearchManager.QUERY);
    311       doMySearch(query);
    312     }
    313 }
    314 </pre>
    315 
    316 <p>The {@link android.app.SearchManager#QUERY QUERY} string is always included with
    317 the {@link android.content.Intent#ACTION_SEARCH} intent. In this example, the query is
    318 retrieved and passed to a local {@code doMySearch()} method where the actual search operation
    319 is done.</p>
    320 
    321 
    322 <h4 id="SearchingYourData">Searching your data</h4>
    323 
    324 <p>The process of storing and searching your data is unique to your application.
    325 You can store and search your data in many ways, but this guide does not show you how to store your
    326 data and search it. Storing and searching your data is something you should carefully consider in
    327 terms of your needs and your data format. However, here are some tips you might be able to
    328 apply:</p>
    329 
    330   <ul>
    331     <li>If your data is stored in a SQLite database on the device, performing a full-text search
    332 (using FTS3, rather than a {@code LIKE} query) can provide a more robust search across text data and
    333 can produce results significantly faster. See <a href="http://sqlite.org/fts3.html">sqlite.org</a>
    334 for information about FTS3 and the {@link android.database.sqlite.SQLiteDatabase} class for
    335 information about SQLite on Android. Also look at the <a
    336 href="{@docRoot}resources/samples/SearchableDictionary/index.html">Searchable Dictionary</a> sample
    337 application to see a complete SQLite implementation that performs searches with FTS3.</li>
    338     <li>If your data is stored online, then the perceived search performance might be
    339 inhibited by the user's data connection. You might want to display a spinning progress wheel until
    340 your search returns. See {@link android.net} for a reference of network APIs and <a
    341 href="{@docRoot}guide/topics/ui/dialogs.html#ProgressDialog">Creating a Progress Dialog</a>
    342 for information about how to display a progress wheel.</li>
    343   </ul>
    344 
    345 
    346 <div class="sidebox-wrapper">
    347 <div class="sidebox">
    348 <h2>About Adapters</h2>
    349 <p>An {@link android.widget.Adapter} binds each item from a set of data into a
    350 {@link android.view.View} object. When the {@link android.widget.Adapter}
    351 is applied to a {@link android.widget.ListView}, each piece of data is inserted as an individual
    352 view into the list. {@link
    353 android.widget.Adapter} is just an interface, so implementations such as {@link
    354 android.widget.CursorAdapter} (for binding data from a {@link android.database.Cursor}) are needed.
    355 If none of the existing implementations work for your data, then you can implement your own from
    356 {@link android.widget.BaseAdapter}. Install the SDK Samples package for API Level 4 to see the
    357 original version of the Searchable Dictionary, which creates a custom adapter to read data from
    358 a file.</p>
    359 </div>
    360 </div>
    361 
    362 <p>Regardless of where your data lives and how you search it, we recommend that you return search
    363 results to your searchable activity with an {@link android.widget.Adapter}. This way, you can easily
    364 present all the search results in a {@link android.widget.ListView}. If your data comes from a
    365 SQLite database query, you can apply your results to a {@link android.widget.ListView}
    366 using a {@link android.widget.CursorAdapter}. If your data comes in some other type of format, then
    367 you can create an extension of {@link android.widget.BaseAdapter}.</p>
    368 
    369 
    370 <h4 id="PresentingTheResults">Presenting the results</h4>
    371 
    372 <p>As discussed above, the recommended UI for your search results is a {@link
    373 android.widget.ListView}, so you might want your searchable activity to extend {@link
    374 android.app.ListActivity}. You can then call {@link
    375 android.app.ListActivity#setListAdapter(ListAdapter) setListAdapter()}, passing it an {@link
    376 android.widget.Adapter} that is bound to your data. This injects all the
    377 search results into the activity {@link android.widget.ListView}.</p>
    378 
    379 <p>For more help presenting your results in a list, see the {@link android.app.ListActivity}
    380 documentation.</p>
    381 
    382 <p>Also see the <a
    383 href="{@docRoot}resources/samples/SearchableDictionary/index.html">Searchable Dictionary</a> sample
    384 for an a complete demonstration of how to search an SQLite database and use an
    385 {@link android.widget.Adapter} to provide results in a {@link android.widget.ListView}.</p>
    386 
    387 
    388 
    389 
    390 
    391 <h2 id="SearchDialog">Using the Search Dialog</h2>
    392 
    393 <div class="sidebox-wrapper">
    394 <div class="sidebox">
    395   <h2>Should I use the search dialog or the widget?</h2>
    396   <p>The answer depends mostly on whether you are developing for Android 3.0 (API Level 11 or
    397 higher), because the {@link android.widget.SearchView} widget was introduced in Android 3.0. So,
    398 if you are developing your application for a version of Android lower than 3.0, the search widget is
    399 not an option and you should use the search dialog to implement your search interface.</p>
    400   <p>If you <em>are</em> developing for Android 3.0 or higher, then the decision depends more on
    401 your needs. In most cases, we recommend that you use the search widget as an "action view" in the
    402 Action Bar. However, it might not be an option for you to put the search
    403 widget in the Action Bar for some reason (perhaps there's not enough space or you don't use the
    404 Action Bar). So, you might instead want to put the search widget somewhere in your activity layout.
    405 And if all else fails, you can still use the search dialog if you prefer to keep the search box
    406 hidden. In fact, you might want to offer both the dialog and the widget in some cases. For more
    407 information about the widget, skip to <a href="#UsingSearchWidget">Using the Search Widget</a>.</p>
    408 </div>
    409 </div>
    410 
    411 <p>The search dialog provides a floating search box at the top of the screen, with the application
    412 icon on the left. The search dialog can provide search suggestions as the user types and, when
    413 the user executes a search, the system sends the search query to a
    414 searchable activity that performs the search. However, if you are developing
    415 your application for devices running Android 3.0, you should consider using the search widget
    416 instead (see the side box).</p>
    417 
    418 <p>The search dialog is always hidden by default, until the user activates it. If the user's device
    419 includes a SEARCH button, pressing it will activate the search dialog by default. Your application
    420 can also activate the search dialog on demand by calling {@link
    421 android.app.Activity#onSearchRequested onSearchRequested()}. However, neither of these work
    422 until you enable the search dialog for the activity.</p>
    423 
    424 <p>To enable the search dialog, you must indicate to the system which searchable activity should
    425 receive search queries from the search dialog, in order to perform searches. For example, in the
    426 previous section about <a href="#SearchableActivity">Creating a Searchable Activity</a>, a
    427 searchable activity named {@code SearchableActivity} was created. If you want a separate activity,
    428 named {@code OtherActivity}, to show the search dialog and deliver searches to {@code
    429 SearchableActivity}, you must declare in the manifest that {@code SearchableActivity} is the
    430 searchable activity to use for the search dialog in {@code OtherActivity}.</p>
    431 
    432 <p>To declare the searchable activity for an activity's search dialog,
    433 add a <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code &lt;meta-data&gt;}</a>
    434 element inside the respective activity's <a
    435 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a> element.
    436 The <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code &lt;meta-data&gt;}</a>
    437 element must include the {@code android:value} attribute that specifies the searchable activity's
    438 class name and the {@code android:name} attribute with a value of {@code
    439 "android.app.default_searchable"}.</p>
    440 
    441 <p>For example, here is the declaration for
    442 both a searchable activity, {@code SearchableActivity}, and another activity, {@code
    443 OtherActivity}, which uses {@code SearchableActivity} to perform searches executed from its
    444 search dialog:</p>
    445 
    446 <pre>
    447 &lt;application ... >
    448     &lt;!-- this is the searchable activity; it performs searches --&gt;
    449     &lt;activity android:name=".SearchableActivity" >
    450         &lt;intent-filter>
    451             &lt;action android:name="android.intent.action.SEARCH" />
    452         &lt;/intent-filter>
    453         &lt;meta-data android:name="android.app.searchable"
    454                    android:resource="@xml/searchable"/>
    455     &lt;/activity>
    456 
    457     &lt;!-- this activity enables the search dialog to initiate searches
    458          in the SearchableActivity --&gt;
    459     &lt;activity android:name=".OtherActivity" ... >
    460         &lt;!-- enable the search dialog to send searches to SearchableActivity -->
    461         <b>&lt;meta-data android:name="android.app.default_searchable"
    462                    android:value=".SearchableActivity" /&gt;</b>
    463     &lt;/activity>
    464     ...
    465 &lt;/application>
    466 </pre>
    467 
    468 <p>Because the {@code OtherActivity} now includes a <a
    469 href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code &lt;meta-data&gt;}</a>
    470 element to declare which searchable activity to use for searches, the activity has enabled the
    471 search dialog.
    472 While the user is in this activity, the device SEARCH button (if available) and the {@link
    473 android.app.Activity#onSearchRequested onSearchRequested()} method will activate the search dialog.
    474 When the user executes the search, the system starts {@code SearchableActivity} and delivers it
    475 the {@link android.content.Intent#ACTION_SEARCH} intent.</p>
    476 
    477 <p class="note"><strong>Note:</strong> The searchable activity itself provides the search dialog
    478 by default, so you don't need to add this declaration to {@code SearchableActivity}.</p>
    479 
    480 <p>If you want every activity in your application to provide the search dialog, insert the above <a
    481 href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code &lt;meta-data&gt;}</a>
    482 element as a child of the <a
    483 href="{@docRoot}guide/topics/manifest/application-element.html">{@code &lt;application&gt;}</a>
    484 element, instead of each <a
    485 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a>. This
    486 way, every activity inherits the value, provides the search dialog, and delivers searches to
    487 the same searchable activity. (If you have multiple searchable activities, you can override the
    488 default searchable activity by placing a different <a
    489 href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code &lt;meta-data&gt;}</a>
    490 declaration inside individual activities.)</p>
    491 
    492 <p>With the search dialog now enabled for your activities, your application is ready to perform
    493 searches.</p>
    494 
    495 
    496 <h3 id="InvokingTheSearchDialog">Invoking the search dialog</h3>
    497 
    498 <p>As mentioned above, the device SEARCH button will open the search dialog as long as the current
    499 activity has declared in the manifest the searchable activity to use.</p>
    500 
    501 <p>However, some devices do not include a dedicated SEARCH button, so you should not assume that
    502 it's always available. When using the search dialog, you must <strong>always provide another search
    503 button in your UI</strong> that activates the search dialog by calling {@link
    504 android.app.Activity#onSearchRequested()}.</p>
    505 
    506 <p>For instance, you should either provide a menu item in your <a
    507 href="{@docRoot}guide/topics/ui/menus.html#options-menu">Options Menu</a> or a button in your
    508 activity layout that
    509 activates search by calling {@link android.app.Activity#onSearchRequested()}. The <a
    510 href="{@docRoot}shareables/search_icons.zip">search_icons.zip</a> file includes icons for
    511 medium and high density screens, which you can use for your search menu item or button (low-density
    512 screens scale-down the hdpi image by one half). </p>
    513 
    514 <p>You can also enable "type-to-search" functionality, which activates the search dialog when the
    515 user starts typing on the keyboard&mdash;the keystrokes are inserted into the search dialog. You can
    516 enable type-to-search in your activity by calling
    517 {@link android.app.Activity#setDefaultKeyMode(int) setDefaultKeyMode}({@link
    518 android.app.Activity#DEFAULT_KEYS_SEARCH_LOCAL}) during your activity's
    519 {@link android.app.Activity#onCreate(Bundle) onCreate()} method.</p>
    520 
    521 
    522 <h3 id="LifeCycle">The impact of the search dialog on your activity lifecycle</h3>
    523 
    524 <p>The search dialog is a {@link android.app.Dialog} that floats at the top of the
    525 screen. It does not cause any change in the activity stack, so when the search dialog appears, no
    526 lifecycle methods (such as {@link android.app.Activity#onPause()}) are called. Your activity just
    527 loses input focus, as input focus is given to the search dialog.
    528 </p>
    529 
    530 <p>If you want to be notified when the search dialog is activated, override the {@link
    531 android.app.Activity#onSearchRequested()} method. When the system calls this method, it is an
    532 indication that your activity has lost input focus to the search dialog, so you can do any
    533 work appropriate for the event (such as pause
    534 a game). Unless you are <a
    535 href="#SearchContextData">passing search context data</a>
    536 (discussed below), you should end the method by calling the super class implementation. For
    537 example:</p>
    538 
    539 <pre>
    540 &#64;Override
    541 public boolean onSearchRequested() {
    542     pauseSomeStuff();
    543     return super.onSearchRequested();
    544 }
    545 </pre>
    546 
    547 <p>If the user cancels search by pressing the <em>Back</em> button, the search dialog closes and the
    548 activity
    549 regains input focus. You can register to be notified when the search dialog is
    550 closed with {@link android.app.SearchManager#setOnDismissListener(SearchManager.OnDismissListener)
    551 setOnDismissListener()}
    552 and/or {@link android.app.SearchManager#setOnCancelListener(SearchManager.OnCancelListener)
    553 setOnCancelListener()}. You
    554 should need to register only the {@link android.app.SearchManager.OnDismissListener
    555 OnDismissListener}, because it is called every time the search dialog closes. The {@link
    556 android.app.SearchManager.OnCancelListener OnCancelListener} only pertains to events in which the
    557 user explicitly exited the search dialog, so it is not called when a search is executed (in which
    558 case, the search dialog naturally disappears).</p>
    559 
    560 <p>If the current activity is not the searchable activity, then the normal activity lifecycle
    561 events are triggered once the user executes a search (the current activity receives {@link
    562 android.app.Activity#onPause()} and so forth, as
    563 described in the <a
    564 href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a>
    565 document). If, however, the current activity is the searchable activity, then one of two
    566 things happens:</p>
    567 
    568 <ol type="a">
    569   <li>By default, the searchable activity receives the {@link
    570 android.content.Intent#ACTION_SEARCH} intent with a call to {@link
    571 android.app.Activity#onCreate(Bundle) onCreate()} and a new instance of the
    572 activity is brought to the top of the activity stack. There are now two instances of your
    573 searchable activity in the activity stack (so pressing the <em>Back</em> button goes back to the
    574 previous
    575 instance of the searchable activity, rather than exiting the searchable activity).</li>
    576   <li>If you set {@code android:launchMode} to <code>"singleTop"</code>, then the
    577 searchable activity receives the {@link android.content.Intent#ACTION_SEARCH} intent with a call
    578 to {@link android.app.Activity#onNewIntent(Intent)}, passing the new {@link
    579 android.content.Intent#ACTION_SEARCH} intent here. For example, here's how you might handle
    580 this case, in which the searchable activity's launch mode is <code>"singleTop"</code>:
    581 <pre>
    582 &#64;Override
    583 public void onCreate(Bundle savedInstanceState) {
    584     super.onCreate(savedInstanceState);
    585     setContentView(R.layout.search);
    586     handleIntent(getIntent());
    587 }
    588 
    589 &#64;Override
    590 protected void onNewIntent(Intent intent) {
    591     setIntent(intent);
    592     handleIntent(intent);
    593 }
    594 
    595 private void handleIntent(Intent intent) {
    596     if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
    597       String query = intent.getStringExtra(SearchManager.QUERY);
    598       doMySearch(query);
    599     }
    600 }
    601 </pre>
    602 
    603 <p>Compared to the example code in the section about <a href="#PerformingSearch">Performing a
    604 Search</a>, all the code to handle the
    605 search intent is now in the {@code handleIntent()} method, so that both {@link
    606 android.app.Activity#onCreate(Bundle)
    607 onCreate()} and {@link android.app.Activity#onNewIntent(Intent) onNewIntent()} can execute it.</p>
    608 
    609 <p>When the system calls {@link android.app.Activity#onNewIntent(Intent)}, the activity has
    610 not been restarted, so the {@link android.app.Activity#getIntent()} method
    611 returns the same intent that was received with {@link
    612 android.app.Activity#onCreate(Bundle) onCreate()}. This is why you should call {@link
    613 android.app.Activity#setIntent(Intent)} inside {@link
    614 android.app.Activity#onNewIntent(Intent)} (so that the intent saved by the activity is updated in
    615 case you call {@link android.app.Activity#getIntent()} in the future).</p>
    616 
    617 </li>
    618 </ol>
    619 
    620 <p>The second scenario using <code>"singleTop"</code> launch mode is usually ideal, because chances
    621 are good that once a search is done, the user will perform additional searches and it's a bad
    622 experience if your application creates multiple instances of the searchable activity. So, we
    623 recommend that you set your searchable activity to <code>"singleTop"</code> launch mode in the
    624 application manifest. For example:</p>
    625 
    626 <pre>
    627 &lt;activity android:name=".SearchableActivity"
    628           <b>android:launchMode="singleTop"</b> >
    629     &lt;intent-filter>
    630         &lt;action android:name="android.intent.action.SEARCH" />
    631     &lt;/intent-filter>
    632     &lt;meta-data android:name="android.app.searchable"
    633                       android:resource="@xml/searchable"/>
    634   &lt;/activity>
    635 </pre>
    636 
    637 
    638 
    639 <h3 id="SearchContextData">Passing search context data</h3>
    640 
    641 <p>In some cases, you can make necessary refinements to the search query inside the searchable
    642 activity, for every search made. However, if you want to refine your search criteria based on the
    643 activity from which the user is performing a search, you can provide additional data in the intent
    644 that the system sends to your searchable activity. You can pass the additional data in the {@link
    645 android.app.SearchManager#APP_DATA} {@link android.os.Bundle}, which is included in the {@link
    646 android.content.Intent#ACTION_SEARCH} intent.</p>
    647 
    648 <p>To pass this kind of data to your searchable activity, override the {@link
    649 android.app.Activity#onSearchRequested()} method for the activity from which the user can perform a
    650 search, create a {@link android.os.Bundle} with the additional data, and call {@link
    651 android.app.Activity#startSearch startSearch()} to activate the search dialog.
    652 For example:</p>
    653 
    654 <pre>
    655 &#64;Override
    656 public boolean onSearchRequested() {
    657      Bundle appData = new Bundle();
    658      appData.putBoolean(SearchableActivity.JARGON, true);
    659      startSearch(null, false, appData, false);
    660      return true;
    661  }
    662 </pre>
    663 
    664 <p>Returning "true" indicates that you have successfully handled this callback event and
    665 called {@link android.app.Activity#startSearch startSearch()} to activate
    666 the search dialog. Once the user submits a query, it's delivered to your
    667 searchable activity along with the data you've added. You can extract the extra data from the {@link
    668 android.app.SearchManager#APP_DATA} {@link android.os.Bundle} to refine the search. For example:</p>
    669 
    670 <pre>
    671 Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA);
    672 if (appData != null) {
    673     boolean jargon = appData.getBoolean(SearchableActivity.JARGON);
    674 }
    675 </pre>
    676 
    677 <p class="caution"><strong>Caution:</strong> Never call the {@link
    678 android.app.Activity#startSearch(String,boolean,Bundle,boolean) startSearch()} method from outside
    679 the {@link android.app.Activity#onSearchRequested()} callback method. To activate the search dialog
    680 in your activity, always call {@link android.app.Activity#onSearchRequested()}. Otherwise, {@link
    681 android.app.Activity#onSearchRequested()} is not called and customizations (such as the addition of
    682 {@code appData} in the above example) are missed.</p>
    683 
    684 
    685 
    686 <h2 id="UsingSearchWidget">Using the Search Widget</h2>
    687 
    688 <div class="figure" style="width:429px;margin:0">
    689   <img src="{@docRoot}images/ui/actionbar-actionview.png" alt="" />
    690   <p class="img-caption"><strong>Figure 2.</strong> The {@link
    691 android.widget.SearchView} widget as an "action view" in the Action Bar.</p>
    692 </div>
    693 
    694 <p>The {@link android.widget.SearchView} widget is available in Android 3.0 and higher. If
    695 you're developing your application for Android 3.0 and have decided to use the search widget, we
    696 recommend that you insert the search widget as an <a
    697 href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">action view in the Action Bar</a>,
    698 instead of using the search dialog (and instead of placing the search widget in your activity
    699 layout). For example, figure 2 shows the search widget in the Action Bar.</p>
    700 
    701 <p>The search widget provides the same functionality as the search dialog. It starts the appropriate
    702 activity when the user executes a search, and it can provide search suggestions and perform voice
    703 search.</p>
    704 
    705 <p class="note"><strong>Note:</strong> When you use the search widget as an action view, you
    706 still might need to support using the search dialog, for cases in which the search widget does
    707 not fit in the Action Bar. See the following section about <a href="#UsingBoth">Using both
    708 the widget and the dialog</a>.</p>
    709 
    710 
    711 <h3 id="ConfiguringWidget">Configuring the search widget</h3>
    712 
    713 <p>After you've created a  <a href="#SearchableConfiguration">searchable configuration</a> and a <a
    714 href="#SearchableActivity">searchable activity</a>, as discussed above, you need to enable assisted
    715 search for each {@link android.widget.SearchView}. You can do so by calling {@link
    716 android.widget.SearchView#setSearchableInfo setSearchableInfo()} and passing it the {@link
    717 android.app.SearchableInfo} object that represents your searchable configuration.</p>
    718 
    719 <p>You can get a reference to the {@link android.app.SearchableInfo} by calling {@link
    720 android.app.SearchManager#getSearchableInfo getSearchableInfo()} on {@link
    721 android.app.SearchManager}.</p>
    722 
    723 <p>For example, if you're using a {@link android.widget.SearchView} as an action view in the <a
    724 href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, you should enable the widget
    725 during the {@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} callback:</p>
    726 
    727 <pre>
    728 &#64;Override
    729 public boolean onCreateOptionsMenu(Menu menu) {
    730     // Inflate the options menu from XML
    731     MenuInflater inflater = getMenuInflater();
    732     inflater.inflate(R.menu.options_menu, menu);
    733 
    734     // Get the SearchView and set the searchable configuration
    735     SearchManager searchManager = (SearchManager) {@link android.app.Activity#getSystemService getSystemService}(Context.SEARCH_SERVICE);
    736     SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    737     searchView.setSearchableInfo(searchManager.getSearchableInfo({@link android.app.Activity#getComponentName()}));
    738     searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
    739 
    740     return true;
    741 }
    742 </pre>
    743 
    744 <p>That's all you need. The search widget is now configured and the system will deliver search
    745 queries to your searchable activity. You can also enable <a href="#SearchSuggestions">search
    746 suggestions</a> for the search widget.</p>
    747 
    748 <p class="note"><strong>Note:</strong> If you want to handle all user input yourself, you can do so
    749 with some callback methods and event listeners. For more information, see the reference
    750 documentation for {@link android.widget.SearchView} and its nested interfaces for the
    751 appropriate event listeners.</p>
    752 
    753 <p>For more information about action views in the Action Bar, read the <a
    754 href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">Action Bar</a> developer guide (which
    755 includes sample code for adding a search widget as an action view).</p>
    756 
    757 
    758 <h3 id="WidgetFeatures">Other search widget features</h3>
    759 
    760 <p>The {@link android.widget.SearchView} widget allows for a few additional features you might
    761 want:</p>
    762 
    763 <dl>
    764   <dt>A submit button</dt>
    765   <dd>By default, there's no button to submit a search query, so the user must press the
    766 "Return" key on the keyboard to initiate a search. You can add a "submit" button by calling
    767 {@link android.widget.SearchView#setSubmitButtonEnabled setSubmitButtonEnabled(true)}.</dd>
    768   <dt>Query refinement for search suggestions</dt>
    769   <dd>When you've enabled search suggestions, you usually expect users to simply select a
    770 suggestion, but they might also want to refine the suggested search query. You can add a button
    771 alongside each suggestion that inserts the suggestion in the search box for refinement by the
    772 user, by calling {@link android.widget.SearchView#setQueryRefinementEnabled
    773 setQueryRefinementEnabled(true)}.</dd>
    774   <dt>The ability to toggle the search box visibility</dt>
    775   <dd>By default, the search widget is "iconified," meaning that it is represented only by a
    776 search icon (a magnifying glass), and expands to show the search box when the user touches it.
    777 As shown above, you can show the search box by default, by calling {@link
    778 android.widget.SearchView#setIconifiedByDefault setIconifiedByDefault(false)}. You can also
    779 toggle the search widget appearance by calling {@link android.widget.SearchView#setIconified
    780 setIconified()}.</dd>
    781 </dl>
    782 
    783 <p>There are several other APIs in the {@link android.widget.SearchView} class that allow you to
    784 customize the search widget. However, most of them are used only when you handle all
    785 user input yourself, instead of using the Android system to deliver search queries and display
    786 search suggestions.</p>
    787 
    788 
    789 <h3 id="UsingBoth">Using both the widget and the dialog</h3>
    790 
    791 <p>If you insert the search widget in the Action Bar as an <a
    792 href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">action view</a>, and you enable it to
    793 appear in the Action Bar "if there is room" (by setting {@code
    794 android:showAsAction="ifRoom"}), then there is a chance that the search widget will not appear
    795 as an action view, but the menu item will appear in the overflow menu. For example, when your
    796 application runs on a smaller screen, there might not be enough room in the Action Bar to display
    797 the search widget along with other action items or navigation elements, so the menu item will
    798 instead appear in the overflow menu. When placed in the overflow menu, the item works like an
    799 ordinary menu item and does not display the action view (the search widget).</p>
    800 
    801 <p>To handle this situation, the menu item to which you've attached the search widget should
    802 activate the search dialog when the user selects it from the overflow menu. In order for it to do
    803 so, you must implement {@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} to
    804 handle the "Search" menu item and open the search dialog by calling {@link
    805 android.app.Activity#onSearchRequested onSearchRequested()}.</p>
    806 
    807 <p>For more information about how items in the Action Bar work and how to handle this situation, see
    808 the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action
    809 Bar</a> developer guide.</p>
    810 
    811 <p>Also see the <a
    812 href="{@docRoot}resources/samples/SearchableDictionary/src/com/example/android/searchabledict/SearchableDictionary.html"
    813 >Searchable Dictionary</a> for an example implementation using
    814 both the dialog and the widget.</p>
    815 
    816 
    817 
    818 <h2 id="VoiceSearch">Adding Voice Search</h2>
    819 
    820 <p>You can add voice search functionality to your search dialog or widget by adding the {@code
    821 android:voiceSearchMode} attribute to your searchable configuration. This adds a voice search
    822 button that launches a voice prompt. When the user
    823 has finished speaking, the transcribed search query is sent to your searchable
    824 activity.</p>
    825 
    826 <p>For example:</p>
    827 
    828 <pre>
    829 &lt;?xml version="1.0" encoding="utf-8"?>
    830 &lt;searchable xmlns:android="http://schemas.android.com/apk/res/android"
    831     android:label="@string/search_label"
    832     android:hint="@string/search_hint"
    833     <b>android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"</b> >
    834 &lt;/searchable>
    835 </pre>
    836 
    837 <p>The value {@code showVoiceSearchButton} is required to enable voice
    838 search, while the second value, {@code launchRecognizer}, specifies that the voice search button
    839 should launch a recognizer that returns the transcribed text to the searchable activity.</p>
    840 
    841 <p>You can provide additional attributes to specify the voice search behavior, such
    842 as the language to be expected and the maximum number of results to return. See the <a
    843 href="searchable-config.html">Searchable Configuration</a> reference for more information about the
    844 available attributes.</p>
    845 
    846 <p class="note"><strong>Note:</strong> Carefully consider whether voice search is appropriate for
    847 your application. All searches performed with the voice search button are immediately sent to
    848 your searchable activity without a chance for the user to review the transcribed query. Sufficiently
    849 test the voice recognition and ensure that it understands the types of queries that
    850 the user might submit inside your application.</p>
    851 
    852 
    853 
    854 <h2 id="SearchSuggestions">Adding Search Suggestions</h2>
    855 
    856 <div class="figure" style="width:250px;margin:0">
    857 <img src="{@docRoot}images/search/search-suggest-custom.png" alt="" height="417" />
    858 <p class="img-caption"><strong>Figure 3.</strong> Screenshot of a search dialog with custom
    859 search suggestions.</p>
    860 </div>
    861 
    862 <p>Both the search dialog and the search widget can provide search suggestions as the user
    863 types, with assistance from the Android system. The system manages the list of suggestions and
    864 handles the event when the user selects a suggestion.</p>
    865 
    866 <p>You can provide two kinds of search suggestions:</p>
    867 
    868 <dl>
    869   <dt>Recent query search suggestions</dt>
    870   <dd>These suggestions are simply words that the user previously used as search queries in
    871 your application.
    872   <p>See <a href="adding-recent-query-suggestions.html">Adding Recent Query
    873 Suggestions</a>.</p></dd>
    874   <dt>Custom search suggestions</dt>
    875   <dd>These are search suggestions that you provide from your own data source, to help users
    876 immediately select the correct spelling or item they are searching for. Figure 3 shows an
    877 example of custom suggestions for a dictionary application&mdash;the user can select a suggestion
    878 to instantly go to the definition.
    879   <p>See <a href="adding-custom-suggestions.html">Adding Custom
    880 Suggestions</a></p></dd>
    881 </dl>
    882 
    883