1page.title=Creating a Search Interface 2parent.title=Search 3parent.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 12specify 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 14access</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 55Dictionary</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 78the user interface with either a search dialog that appears at the top of the activity window or a 79search widget that you can insert in your layout. Both the search dialog and the widget can deliver 80the user's search query to a specific activity in your application. This way, the user can initiate 81a search from any activity where the search dialog or widget is available, and the system starts the 82appropriate 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 93that's assisted by the Android system to deliver search queries, using either the 94search 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 105search dialog or the search widget. Both provide the same search features, but in slightly different 106ways:</p> 107 108<ul> 109 <li>The <strong>search dialog</strong> is a UI component that's controlled by the Android system. 110When activated by the user, the search dialog appears at the top of the activity, as shown in figure 1111. 112 <p>The Android system controls all events in the search dialog. When the user 113submits a query, the system delivers the query to the activity that you specify to 114handle 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 117you can place anywhere in your layout. By default, the search widget behaves like a standard {@link 118android.widget.EditText} widget and doesn't do anything, but you can configure it so that the 119Android system handles all input events, delivers queries to the appropriate activity, and provides 120search suggestions (just like the search dialog). However, the search widget is available only in 121Android 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 124search widget yourself, using various callback methods and listeners. This document, however, 125focuses on how to integrate the search widget with the system for an assisted search 126implementation. 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 132that you've declared to handle searches (the "searchable activity") and delivers it the intent. To 133set 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 138for 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 141data, 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 146user 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. 150Instead 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 158activity, 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 164certain UI aspects of the search dialog or widget and defines how features such as suggestions and 165voice search behave. This file is traditionally named {@code searchable.xml} and must be saved in 166the {@code res/xml/} project directory.</p> 167 168<p class="note"><strong>Note:</strong> The system uses this file to instantiate a {@link 169android.app.SearchableInfo} object, but you cannot create this object yourself at 170runtime—you must declare the searchable configuration in XML.</p> 171 172<p>The searchable configuration file must include the <a 173href="{@docRoot}guide/topics/search/searchable-config.html#searchable-element">{@code 174<searchable>}</a> element as the root node and specify one 175or more attributes. For example:</p> 176 177<pre> 178<?xml version="1.0" encoding="utf-8"?> 179<searchable xmlns:android="http://schemas.android.com/apk/res/android" 180 android:label="@string/app_label" 181 android:hint="@string/search_hint" > 182</searchable> 183</pre> 184 185<p>The {@code android:label} attribute is the only required attribute. It points to a string 186resource, which should be the application name. This label isn't actually visible to the 187user until you enable search suggestions for Quick Search Box. At that point, this label is visible 188in 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} 191attribute, which provides a hint string in the search box before users 192enters a query. The hint is important because it provides important clues to users about what 193they can search.</p> 194 195<p class="note"><strong>Tip:</strong> For consistency among other 196Android applications, you should format the string for {@code android:hint} as "Search 197<content-or-product>". For example, "Search songs and artists" or "Search 198YouTube".</p> 199 200<p>The <a 201href="{@docRoot}guide/topics/search/searchable-config.html#searchable-element">{@code 202<searchable>}</a> element accepts several other attributes. However, you don't need 203most attributes until you add features such as <a href="#SearchSuggestions">search suggestions</a> 204and <a href="#VoiceSearch">voice search</a>. For detailed information about the searchable 205configuration file, see the <a 206href="{@docRoot}guide/topics/search/searchable-config.html">Searchable Configuration</a> reference 207document.</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 214searches 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 217searchable activity and delivers it the search query in an {@link 218android.content.Intent} with the {@link android.content.Intent#ACTION_SEARCH} action. Your 219searchable activity retrieves the query from the intent's {@link android.app.SearchManager#QUERY 220QUERY} 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, 223the system must know which activity is your searchable activity, so it can properly deliver the 224search 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 230searches and present results. You don't need to implement the search functionality yet—just 231create an activity that you can declare in the manifest. Inside the manifest's <a 232href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> 233element:</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<intent-filter>}</a> 238element.</li> 239 <li>Specify the searchable configuration to use, in a <a 240href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code <meta-data>}</a> 241element.</li> 242</ol> 243 244<p>For example:</p> 245 246<pre> 247<application ... > 248 <activity android:name=".SearchableActivity" > 249 <intent-filter> 250 <action android:name="android.intent.action.SEARCH" /> 251 </intent-filter> 252 <meta-data android:name="android.app.searchable" 253 android:resource="@xml/searchable"/> 254 </activity> 255 ... 256</application> 257</pre> 258 259<p>The {@code <meta-data>} element must include the {@code android:name} attribute with a 260value of {@code "android.app.searchable"} and the {@code android:resource} attribute with a 261reference to the searchable configuration file (in this example, it 262refers to the {@code res/xml/searchable.xml} file).</p> 263 264<p class="note"><strong>Note:</strong> The <a 265href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code 266<intent-filter>}</a> does not need a <a 267href="{@docRoot}guide/topics/manifest/category-element.html">{@code <category>}</a> with the 268{@code DEFAULT} value (which you usually see in <a 269href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> elements), 270because the system delivers the {@link android.content.Intent#ACTION_SEARCH} intent explicitly to 271your 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 278searchable 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 287you might want your searchable activity to extend {@link android.app.ListActivity}. It includes 288a default layout with a single {@link android.widget.ListView} and provides several 289convenience 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 295searchable activity and sends it a {@link android.content.Intent#ACTION_SEARCH} intent. This intent 296carries the search query in the 297{@link android.app.SearchManager#QUERY QUERY} string extra. You must check for 298this intent when the activity starts and extract the string. For example, here's how you can get the 299search query when your searchable activity starts:</p> 300 301<pre> 302@Override 303public 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 317the {@link android.content.Intent#ACTION_SEARCH} intent. In this example, the query is 318retrieved and passed to a local {@code doMySearch()} method where the actual search operation 319is 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. 325You can store and search your data in many ways, but this guide does not show you how to store your 326data and search it. Storing and searching your data is something you should carefully consider in 327terms of your needs and your data format. However, here are some tips you might be able to 328apply:</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 333can produce results significantly faster. See <a href="http://sqlite.org/fts3.html">sqlite.org</a> 334for information about FTS3 and the {@link android.database.sqlite.SQLiteDatabase} class for 335information about SQLite on Android. Also look at the <a 336href="{@docRoot}resources/samples/SearchableDictionary/index.html">Searchable Dictionary</a> sample 337application 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 339inhibited by the user's data connection. You might want to display a spinning progress wheel until 340your search returns. See {@link android.net} for a reference of network APIs and <a 341href="{@docRoot}guide/topics/ui/dialogs.html#ProgressDialog">Creating a Progress Dialog</a> 342for 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} 351is applied to a {@link android.widget.ListView}, each piece of data is inserted as an individual 352view into the list. {@link 353android.widget.Adapter} is just an interface, so implementations such as {@link 354android.widget.CursorAdapter} (for binding data from a {@link android.database.Cursor}) are needed. 355If 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 357original version of the Searchable Dictionary, which creates a custom adapter to read data from 358a 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 363results to your searchable activity with an {@link android.widget.Adapter}. This way, you can easily 364present all the search results in a {@link android.widget.ListView}. If your data comes from a 365SQLite database query, you can apply your results to a {@link android.widget.ListView} 366using a {@link android.widget.CursorAdapter}. If your data comes in some other type of format, then 367you 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 373android.widget.ListView}, so you might want your searchable activity to extend {@link 374android.app.ListActivity}. You can then call {@link 375android.app.ListActivity#setListAdapter(ListAdapter) setListAdapter()}, passing it an {@link 376android.widget.Adapter} that is bound to your data. This injects all the 377search 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} 380documentation.</p> 381 382<p>Also see the <a 383href="{@docRoot}resources/samples/SearchableDictionary/index.html">Searchable Dictionary</a> sample 384for 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 397higher), because the {@link android.widget.SearchView} widget was introduced in Android 3.0. So, 398if you are developing your application for a version of Android lower than 3.0, the search widget is 399not 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 401your needs. In most cases, we recommend that you use the search widget as an "action view" in the 402Action Bar. However, it might not be an option for you to put the search 403widget in the Action Bar for some reason (perhaps there's not enough space or you don't use the 404Action Bar). So, you might instead want to put the search widget somewhere in your activity layout. 405And if all else fails, you can still use the search dialog if you prefer to keep the search box 406hidden. In fact, you might want to offer both the dialog and the widget in some cases. For more 407information 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 412icon on the left. The search dialog can provide search suggestions as the user types and, when 413the user executes a search, the system sends the search query to a 414searchable activity that performs the search. However, if you are developing 415your application for devices running Android 3.0, you should consider using the search widget 416instead (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 419includes a SEARCH button, pressing it will activate the search dialog by default. Your application 420can also activate the search dialog on demand by calling {@link 421android.app.Activity#onSearchRequested onSearchRequested()}. However, neither of these work 422until 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 425receive search queries from the search dialog, in order to perform searches. For example, in the 426previous section about <a href="#SearchableActivity">Creating a Searchable Activity</a>, a 427searchable activity named {@code SearchableActivity} was created. If you want a separate activity, 428named {@code OtherActivity}, to show the search dialog and deliver searches to {@code 429SearchableActivity}, you must declare in the manifest that {@code SearchableActivity} is the 430searchable 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, 433add a <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code <meta-data>}</a> 434element inside the respective activity's <a 435href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element. 436The <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code <meta-data>}</a> 437element must include the {@code android:value} attribute that specifies the searchable activity's 438class 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 442both a searchable activity, {@code SearchableActivity}, and another activity, {@code 443OtherActivity}, which uses {@code SearchableActivity} to perform searches executed from its 444search dialog:</p> 445 446<pre> 447<application ... > 448 <!-- this is the searchable activity; it performs searches --> 449 <activity android:name=".SearchableActivity" > 450 <intent-filter> 451 <action android:name="android.intent.action.SEARCH" /> 452 </intent-filter> 453 <meta-data android:name="android.app.searchable" 454 android:resource="@xml/searchable"/> 455 </activity> 456 457 <!-- this activity enables the search dialog to initiate searches 458 in the SearchableActivity --> 459 <activity android:name=".OtherActivity" ... > 460 <!-- enable the search dialog to send searches to SearchableActivity --> 461 <b><meta-data android:name="android.app.default_searchable" 462 android:value=".SearchableActivity" /></b> 463 </activity> 464 ... 465</application> 466</pre> 467 468<p>Because the {@code OtherActivity} now includes a <a 469href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code <meta-data>}</a> 470element to declare which searchable activity to use for searches, the activity has enabled the 471search dialog. 472While the user is in this activity, the device SEARCH button (if available) and the {@link 473android.app.Activity#onSearchRequested onSearchRequested()} method will activate the search dialog. 474When the user executes the search, the system starts {@code SearchableActivity} and delivers it 475the {@link android.content.Intent#ACTION_SEARCH} intent.</p> 476 477<p class="note"><strong>Note:</strong> The searchable activity itself provides the search dialog 478by 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 481href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code <meta-data>}</a> 482element as a child of the <a 483href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> 484element, instead of each <a 485href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a>. This 486way, every activity inherits the value, provides the search dialog, and delivers searches to 487the same searchable activity. (If you have multiple searchable activities, you can override the 488default searchable activity by placing a different <a 489href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code <meta-data>}</a> 490declaration inside individual activities.)</p> 491 492<p>With the search dialog now enabled for your activities, your application is ready to perform 493searches.</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 499activity 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 502it's always available. When using the search dialog, you must <strong>always provide another search 503button in your UI</strong> that activates the search dialog by calling {@link 504android.app.Activity#onSearchRequested()}.</p> 505 506<p>For instance, you should either provide a menu item in your <a 507href="{@docRoot}guide/topics/ui/menus.html#options-menu">Options Menu</a> or a button in your 508activity layout that 509activates search by calling {@link android.app.Activity#onSearchRequested()}. The <a 510href="{@docRoot}shareables/search_icons.zip">search_icons.zip</a> file includes icons for 511medium and high density screens, which you can use for your search menu item or button (low-density 512screens 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 515user starts typing on the keyboard—the keystrokes are inserted into the search dialog. You can 516enable type-to-search in your activity by calling 517{@link android.app.Activity#setDefaultKeyMode(int) setDefaultKeyMode}({@link 518android.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 525screen. It does not cause any change in the activity stack, so when the search dialog appears, no 526lifecycle methods (such as {@link android.app.Activity#onPause()}) are called. Your activity just 527loses 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 531android.app.Activity#onSearchRequested()} method. When the system calls this method, it is an 532indication that your activity has lost input focus to the search dialog, so you can do any 533work appropriate for the event (such as pause 534a game). Unless you are <a 535href="#SearchContextData">passing search context data</a> 536(discussed below), you should end the method by calling the super class implementation. For 537example:</p> 538 539<pre> 540@Override 541public boolean onSearchRequested() { 542 pauseSomeStuff(); 543 return super.onSearchRequested(); 544} 545</pre> 546 547<p>If the user cancels search by pressing the BACK button, the search dialog closes and the activity 548regains input focus. You can register to be notified when the search dialog is 549closed with {@link android.app.SearchManager#setOnDismissListener(SearchManager.OnDismissListener) 550setOnDismissListener()} 551and/or {@link android.app.SearchManager#setOnCancelListener(SearchManager.OnCancelListener) 552setOnCancelListener()}. You 553should need to register only the {@link android.app.SearchManager.OnDismissListener 554OnDismissListener}, because it is called every time the search dialog closes. The {@link 555android.app.SearchManager.OnCancelListener OnCancelListener} only pertains to events in which the 556user explicitly exited the search dialog, so it is not called when a search is executed (in which 557case, the search dialog naturally disappears).</p> 558 559<p>If the current activity is not the searchable activity, then the normal activity lifecycle 560events are triggered once the user executes a search (the current activity receives {@link 561android.app.Activity#onPause()} and so forth, as 562described in the <a 563href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a> 564document). If, however, the current activity is the searchable activity, then one of two 565things happens:</p> 566 567<ol type="a"> 568 <li>By default, the searchable activity receives the {@link 569android.content.Intent#ACTION_SEARCH} intent with a call to {@link 570android.app.Activity#onCreate(Bundle) onCreate()} and a new instance of the 571activity is brought to the top of the activity stack. There are now two instances of your 572searchable activity in the activity stack (so pressing the BACK button goes back to the previous 573instance of the searchable activity, rather than exiting the searchable activity).</li> 574 <li>If you set {@code android:launchMode} to <code>"singleTop"</code>, then the 575searchable activity receives the {@link android.content.Intent#ACTION_SEARCH} intent with a call 576to {@link android.app.Activity#onNewIntent(Intent)}, passing the new {@link 577android.content.Intent#ACTION_SEARCH} intent here. For example, here's how you might handle 578this case, in which the searchable activity's launch mode is <code>"singleTop"</code>: 579<pre> 580@Override 581public void onCreate(Bundle savedInstanceState) { 582 super.onCreate(savedInstanceState); 583 setContentView(R.layout.search); 584 handleIntent(getIntent()); 585} 586 587@Override 588protected void onNewIntent(Intent intent) { 589 setIntent(intent); 590 handleIntent(intent); 591} 592 593private void handleIntent(Intent intent) { 594 if (Intent.ACTION_SEARCH.equals(intent.getAction())) { 595 String query = intent.getStringExtra(SearchManager.QUERY); 596 doMySearch(query); 597 } 598} 599</pre> 600 601<p>Compared to the example code in the section about <a href="#PerformingSearch">Performing a 602Search</a>, all the code to handle the 603search intent is now in the {@code handleIntent()} method, so that both {@link 604android.app.Activity#onCreate(Bundle) 605onCreate()} and {@link android.app.Activity#onNewIntent(Intent) onNewIntent()} can execute it.</p> 606 607<p>When the system calls {@link android.app.Activity#onNewIntent(Intent)}, the activity has 608not been restarted, so the {@link android.app.Activity#getIntent()} method 609returns the same intent that was received with {@link 610android.app.Activity#onCreate(Bundle) onCreate()}. This is why you should call {@link 611android.app.Activity#setIntent(Intent)} inside {@link 612android.app.Activity#onNewIntent(Intent)} (so that the intent saved by the activity is updated in 613case you call {@link android.app.Activity#getIntent()} in the future).</p> 614 615</li> 616</ol> 617 618<p>The second scenario using <code>"singleTop"</code> launch mode is usually ideal, because chances 619are good that once a search is done, the user will perform additional searches and it's a bad 620experience if your application creates multiple instances of the searchable activity. So, we 621recommend that you set your searchable activity to <code>"singleTop"</code> launch mode in the 622application manifest. For example:</p> 623 624<pre> 625<activity android:name=".SearchableActivity" 626 <b>android:launchMode="singleTop"</b> > 627 <intent-filter> 628 <action android:name="android.intent.action.SEARCH" /> 629 </intent-filter> 630 <meta-data android:name="android.app.searchable" 631 android:resource="@xml/searchable"/> 632 </activity> 633</pre> 634 635 636 637<h3 id="SearchContextData">Passing search context data</h3> 638 639<p>In some cases, you can make necessary refinements to the search query inside the searchable 640activity, for every search made. However, if you want to refine your search criteria based on the 641activity from which the user is performing a search, you can provide additional data in the intent 642that the system sends to your searchable activity. You can pass the additional data in the {@link 643android.app.SearchManager#APP_DATA} {@link android.os.Bundle}, which is included in the {@link 644android.content.Intent#ACTION_SEARCH} intent.</p> 645 646<p>To pass this kind of data to your searchable activity, override the {@link 647android.app.Activity#onSearchRequested()} method for the activity from which the user can perform a 648search, create a {@link android.os.Bundle} with the additional data, and call {@link 649android.app.Activity#startSearch startSearch()} to activate the search dialog. 650For example:</p> 651 652<pre> 653@Override 654public boolean onSearchRequested() { 655 Bundle appData = new Bundle(); 656 appData.putBoolean(SearchableActivity.JARGON, true); 657 startSearch(null, false, appData, false); 658 return true; 659 } 660</pre> 661 662<p>Returning "true" indicates that you have successfully handled this callback event and 663called {@link android.app.Activity#startSearch startSearch()} to activate 664the search dialog. Once the user submits a query, it's delivered to your 665searchable activity along with the data you've added. You can extract the extra data from the {@link 666android.app.SearchManager#APP_DATA} {@link android.os.Bundle} to refine the search. For example:</p> 667 668<pre> 669Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA); 670if (appData != null) { 671 boolean jargon = appData.getBoolean(SearchableActivity.JARGON); 672} 673</pre> 674 675<p class="caution"><strong>Caution:</strong> Never call the {@link 676android.app.Activity#startSearch(String,boolean,Bundle,boolean) startSearch()} method from outside 677the {@link android.app.Activity#onSearchRequested()} callback method. To activate the search dialog 678in your activity, always call {@link android.app.Activity#onSearchRequested()}. Otherwise, {@link 679android.app.Activity#onSearchRequested()} is not called and customizations (such as the addition of 680{@code appData} in the above example) are missed.</p> 681 682 683 684<h2 id="UsingSearchWidget">Using the Search Widget</h2> 685 686<div class="figure" style="width:429px;margin:0"> 687 <img src="{@docRoot}images/ui/actionbar-actionview.png" alt="" /> 688 <p class="img-caption"><strong>Figure 2.</strong> The {@link 689android.widget.SearchView} widget as an "action view" in the Action Bar.</p> 690</div> 691 692<p>The {@link android.widget.SearchView} widget is available in Android 3.0 and higher. If 693you're developing your application for Android 3.0 and have decided to use the search widget, we 694recommend that you insert the search widget as an <a 695href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">action view in the Action Bar</a>, 696instead of using the search dialog (and instead of placing the search widget in your activity 697layout). For example, figure 2 shows the search widget in the Action Bar.</p> 698 699<p>The search widget provides the same functionality as the search dialog. It starts the appropriate 700activity when the user executes a search, and it can provide search suggestions and perform voice 701search.</p> 702 703<p class="note"><strong>Note:</strong> When you use the search widget as an action view, you 704still might need to support using the search dialog, for cases in which the search widget does 705not fit in the Action Bar. See the following section about <a href="#UsingBoth">Using both 706the widget and the dialog</a>.</p> 707 708 709<h3 id="ConfiguringWidget">Configuring the search widget</h3> 710 711<p>After you've created a <a href="#SearchableConfiguration">searchable configuration</a> and a <a 712href="#SearchableActivity">searchable activity</a>, as discussed above, you need to enable assisted 713search for each {@link android.widget.SearchView}. You can do so by calling {@link 714android.widget.SearchView#setSearchableInfo setSearchableInfo()} and passing it the {@link 715android.app.SearchableInfo} object that represents your searchable configuration.</p> 716 717<p>You can get a reference to the {@link android.app.SearchableInfo} by calling {@link 718android.app.SearchManager#getSearchableInfo getSearchableInfo()} on {@link 719android.app.SearchManager}.</p> 720 721<p>For example, if you're using a {@link android.widget.SearchView} as an action view in the <a 722href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, you should enable the widget 723during the {@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} callback:</p> 724 725<pre> 726@Override 727public boolean onCreateOptionsMenu(Menu menu) { 728 // Inflate the options menu from XML 729 MenuInflater inflater = getMenuInflater(); 730 inflater.inflate(R.menu.options_menu, menu); 731 732 // Get the SearchView and set the searchable configuration 733 SearchManager searchManager = (SearchManager) {@link android.app.Activity#getSystemService getSystemService}(Context.SEARCH_SERVICE); 734 SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); 735 searchView.setSearchableInfo(searchManager.getSearchableInfo({@link android.app.Activity#getComponentName()})); 736 searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default 737 738 return true; 739} 740</pre> 741 742<p>That's all you need. The search widget is now configured and the system will deliver search 743queries to your searchable activity. You can also enable <a href="#SearchSuggestions">search 744suggestions</a> for the search widget.</p> 745 746<p class="note"><strong>Note:</strong> If you want to handle all user input yourself, you can do so 747with some callback methods and event listeners. For more information, see the reference 748documentation for {@link android.widget.SearchView} and its nested interfaces for the 749appropriate event listeners.</p> 750 751<p>For more information about action views in the Action Bar, read the <a 752href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">Action Bar</a> developer guide (which 753includes sample code for adding a search widget as an action view).</p> 754 755 756<h3 id="WidgetFeatures">Other search widget features</h3> 757 758<p>The {@link android.widget.SearchView} widget allows for a few additional features you might 759want:</p> 760 761<dl> 762 <dt>A submit button</dt> 763 <dd>By default, there's no button to submit a search query, so the user must press the 764"Return" key on the keyboard to initiate a search. You can add a "submit" button by calling 765{@link android.widget.SearchView#setSubmitButtonEnabled setSubmitButtonEnabled(true)}.</dd> 766 <dt>Query refinement for search suggestions</dt> 767 <dd>When you've enabled search suggestions, you usually expect users to simply select a 768suggestion, but they might also want to refine the suggested search query. You can add a button 769alongside each suggestion that inserts the suggestion in the search box for refinement by the 770user, by calling {@link android.widget.SearchView#setQueryRefinementEnabled 771setQueryRefinementEnabled(true)}.</dd> 772 <dt>The ability to toggle the search box visibility</dt> 773 <dd>By default, the search widget is "iconified," meaning that it is represented only by a 774search icon (a magnifying glass), and expands to show the search box when the user touches it. 775As shown above, you can show the search box by default, by calling {@link 776android.widget.SearchView#setIconifiedByDefault setIconifiedByDefault(false)}. You can also 777toggle the search widget appearance by calling {@link android.widget.SearchView#setIconified 778setIconified()}.</dd> 779</dl> 780 781<p>There are several other APIs in the {@link android.widget.SearchView} class that allow you to 782customize the search widget. However, most of them are used only when you handle all 783user input yourself, instead of using the Android system to deliver search queries and display 784search suggestions.</p> 785 786 787<h3 id="UsingBoth">Using both the widget and the dialog</h3> 788 789<p>If you insert the search widget in the Action Bar as an <a 790href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">action view</a>, and you enable it to 791appear in the Action Bar "if there is room" (by setting {@code 792android:showAsAction="ifRoom"}), then there is a chance that the search widget will not appear 793as an action view, but the menu item will appear in the overflow menu. For example, when your 794application runs on a smaller screen, there might not be enough room in the Action Bar to display 795the search widget along with other action items or navigation elements, so the menu item will 796instead appear in the overflow menu. When placed in the overflow menu, the item works like an 797ordinary menu item and does not display the action view (the search widget).</p> 798 799<p>To handle this situation, the menu item to which you've attached the search widget should 800activate the search dialog when the user selects it from the overflow menu. In order for it to do 801so, you must implement {@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} to 802handle the "Search" menu item and open the search dialog by calling {@link 803android.app.Activity#onSearchRequested onSearchRequested()}.</p> 804 805<p>For more information about how items in the Action Bar work and how to handle this situation, see 806the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action 807Bar</a> developer guide.</p> 808 809<p>Also see the <a 810href="{@docRoot}resources/samples/SearchableDictionary/src/com/example/android/searchabledict/SearchableDictionary.html" 811>Searchable Dictionary</a> for an example implementation using 812both the dialog and the widget.</p> 813 814 815 816<h2 id="VoiceSearch">Adding Voice Search</h2> 817 818<p>You can add voice search functionality to your search dialog or widget by adding the {@code 819android:voiceSearchMode} attribute to your searchable configuration. This adds a voice search 820button that launches a voice prompt. When the user 821has finished speaking, the transcribed search query is sent to your searchable 822activity.</p> 823 824<p>For example:</p> 825 826<pre> 827<?xml version="1.0" encoding="utf-8"?> 828<searchable xmlns:android="http://schemas.android.com/apk/res/android" 829 android:label="@string/search_label" 830 android:hint="@string/search_hint" 831 <b>android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"</b> > 832</searchable> 833</pre> 834 835<p>The value {@code showVoiceSearchButton} is required to enable voice 836search, while the second value, {@code launchRecognizer}, specifies that the voice search button 837should launch a recognizer that returns the transcribed text to the searchable activity.</p> 838 839<p>You can provide additional attributes to specify the voice search behavior, such 840as the language to be expected and the maximum number of results to return. See the <a 841href="searchable-config.html">Searchable Configuration</a> reference for more information about the 842available attributes.</p> 843 844<p class="note"><strong>Note:</strong> Carefully consider whether voice search is appropriate for 845your application. All searches performed with the voice search button are immediately sent to 846your searchable activity without a chance for the user to review the transcribed query. Sufficiently 847test the voice recognition and ensure that it understands the types of queries that 848the user might submit inside your application.</p> 849 850 851 852<h2 id="SearchSuggestions">Adding Search Suggestions</h2> 853 854<div class="figure" style="width:250px;margin:0"> 855<img src="{@docRoot}images/search/search-suggest-custom.png" alt="" height="417" /> 856<p class="img-caption"><strong>Figure 3.</strong> Screenshot of a search dialog with custom 857search suggestions.</p> 858</div> 859 860<p>Both the search dialog and the search widget can provide search suggestions as the user 861types, with assistance from the Android system. The system manages the list of suggestions and 862handles the event when the user selects a suggestion.</p> 863 864<p>You can provide two kinds of search suggestions:</p> 865 866<dl> 867 <dt>Recent query search suggestions</dt> 868 <dd>These suggestions are simply words that the user previously used as search queries in 869your application. 870 <p>See <a href="adding-recent-query-suggestions.html">Adding Recent Query 871Suggestions</a>.</p></dd> 872 <dt>Custom search suggestions</dt> 873 <dd>These are search suggestions that you provide from your own data source, to help users 874immediately select the correct spelling or item they are searching for. Figure 3 shows an 875example of custom suggestions for a dictionary application—the user can select a suggestion 876to instantly go to the definition. 877 <p>See <a href="adding-custom-suggestions.html">Adding Custom 878Suggestions</a></p></dd> 879</dl> 880 881