search-dialog.jd revision 50e990c64fa23ce94efa76b9e72df7f8ec3cee6a
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 <em>Back</em> button, the search dialog closes and the 548activity 549regains input focus. You can register to be notified when the search dialog is 550closed with {@link android.app.SearchManager#setOnDismissListener(SearchManager.OnDismissListener) 551setOnDismissListener()} 552and/or {@link android.app.SearchManager#setOnCancelListener(SearchManager.OnCancelListener) 553setOnCancelListener()}. You 554should need to register only the {@link android.app.SearchManager.OnDismissListener 555OnDismissListener}, because it is called every time the search dialog closes. The {@link 556android.app.SearchManager.OnCancelListener OnCancelListener} only pertains to events in which the 557user explicitly exited the search dialog, so it is not called when a search is executed (in which 558case, the search dialog naturally disappears).</p> 559 560<p>If the current activity is not the searchable activity, then the normal activity lifecycle 561events are triggered once the user executes a search (the current activity receives {@link 562android.app.Activity#onPause()} and so forth, as 563described in the <a 564href="{@docRoot}guide/components/activities.html#Lifecycle">Activities</a> 565document). If, however, the current activity is the searchable activity, then one of two 566things happens:</p> 567 568<ol type="a"> 569 <li>By default, the searchable activity receives the {@link 570android.content.Intent#ACTION_SEARCH} intent with a call to {@link 571android.app.Activity#onCreate(Bundle) onCreate()} and a new instance of the 572activity is brought to the top of the activity stack. There are now two instances of your 573searchable activity in the activity stack (so pressing the <em>Back</em> button goes back to the 574previous 575instance 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 577searchable activity receives the {@link android.content.Intent#ACTION_SEARCH} intent with a call 578to {@link android.app.Activity#onNewIntent(Intent)}, passing the new {@link 579android.content.Intent#ACTION_SEARCH} intent here. For example, here's how you might handle 580this case, in which the searchable activity's launch mode is <code>"singleTop"</code>: 581<pre> 582@Override 583public void onCreate(Bundle savedInstanceState) { 584 super.onCreate(savedInstanceState); 585 setContentView(R.layout.search); 586 handleIntent(getIntent()); 587} 588 589@Override 590protected void onNewIntent(Intent intent) { 591 setIntent(intent); 592 handleIntent(intent); 593} 594 595private 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 604Search</a>, all the code to handle the 605search intent is now in the {@code handleIntent()} method, so that both {@link 606android.app.Activity#onCreate(Bundle) 607onCreate()} 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 610not been restarted, so the {@link android.app.Activity#getIntent()} method 611returns the same intent that was received with {@link 612android.app.Activity#onCreate(Bundle) onCreate()}. This is why you should call {@link 613android.app.Activity#setIntent(Intent)} inside {@link 614android.app.Activity#onNewIntent(Intent)} (so that the intent saved by the activity is updated in 615case 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 621are good that once a search is done, the user will perform additional searches and it's a bad 622experience if your application creates multiple instances of the searchable activity. So, we 623recommend that you set your searchable activity to <code>"singleTop"</code> launch mode in the 624application manifest. For example:</p> 625 626<pre> 627<activity android:name=".SearchableActivity" 628 <b>android:launchMode="singleTop"</b> > 629 <intent-filter> 630 <action android:name="android.intent.action.SEARCH" /> 631 </intent-filter> 632 <meta-data android:name="android.app.searchable" 633 android:resource="@xml/searchable"/> 634 </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 642activity, for every search made. However, if you want to refine your search criteria based on the 643activity from which the user is performing a search, you can provide additional data in the intent 644that the system sends to your searchable activity. You can pass the additional data in the {@link 645android.app.SearchManager#APP_DATA} {@link android.os.Bundle}, which is included in the {@link 646android.content.Intent#ACTION_SEARCH} intent.</p> 647 648<p>To pass this kind of data to your searchable activity, override the {@link 649android.app.Activity#onSearchRequested()} method for the activity from which the user can perform a 650search, create a {@link android.os.Bundle} with the additional data, and call {@link 651android.app.Activity#startSearch startSearch()} to activate the search dialog. 652For example:</p> 653 654<pre> 655@Override 656public 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 665called {@link android.app.Activity#startSearch startSearch()} to activate 666the search dialog. Once the user submits a query, it's delivered to your 667searchable activity along with the data you've added. You can extract the extra data from the {@link 668android.app.SearchManager#APP_DATA} {@link android.os.Bundle} to refine the search. For example:</p> 669 670<pre> 671Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA); 672if (appData != null) { 673 boolean jargon = appData.getBoolean(SearchableActivity.JARGON); 674} 675</pre> 676 677<p class="caution"><strong>Caution:</strong> Never call the {@link 678android.app.Activity#startSearch(String,boolean,Bundle,boolean) startSearch()} method from outside 679the {@link android.app.Activity#onSearchRequested()} callback method. To activate the search dialog 680in your activity, always call {@link android.app.Activity#onSearchRequested()}. Otherwise, {@link 681android.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 691android.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 695you're developing your application for Android 3.0 and have decided to use the search widget, we 696recommend that you insert the search widget as an <a 697href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">action view in the Action Bar</a>, 698instead of using the search dialog (and instead of placing the search widget in your activity 699layout). 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 702activity when the user executes a search, and it can provide search suggestions and perform voice 703search.</p> 704 705<p class="note"><strong>Note:</strong> When you use the search widget as an action view, you 706still might need to support using the search dialog, for cases in which the search widget does 707not fit in the Action Bar. See the following section about <a href="#UsingBoth">Using both 708the 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 714href="#SearchableActivity">searchable activity</a>, as discussed above, you need to enable assisted 715search for each {@link android.widget.SearchView}. You can do so by calling {@link 716android.widget.SearchView#setSearchableInfo setSearchableInfo()} and passing it the {@link 717android.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 720android.app.SearchManager#getSearchableInfo getSearchableInfo()} on {@link 721android.app.SearchManager}.</p> 722 723<p>For example, if you're using a {@link android.widget.SearchView} as an action view in the <a 724href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, you should enable the widget 725during the {@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} callback:</p> 726 727<pre> 728@Override 729public 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 745queries to your searchable activity. You can also enable <a href="#SearchSuggestions">search 746suggestions</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 749with some callback methods and event listeners. For more information, see the reference 750documentation for {@link android.widget.SearchView} and its nested interfaces for the 751appropriate event listeners.</p> 752 753<p>For more information about action views in the Action Bar, read the <a 754href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">Action Bar</a> developer guide (which 755includes 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 761want:</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 770suggestion, but they might also want to refine the suggested search query. You can add a button 771alongside each suggestion that inserts the suggestion in the search box for refinement by the 772user, by calling {@link android.widget.SearchView#setQueryRefinementEnabled 773setQueryRefinementEnabled(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 776search icon (a magnifying glass), and expands to show the search box when the user touches it. 777As shown above, you can show the search box by default, by calling {@link 778android.widget.SearchView#setIconifiedByDefault setIconifiedByDefault(false)}. You can also 779toggle the search widget appearance by calling {@link android.widget.SearchView#setIconified 780setIconified()}.</dd> 781</dl> 782 783<p>There are several other APIs in the {@link android.widget.SearchView} class that allow you to 784customize the search widget. However, most of them are used only when you handle all 785user input yourself, instead of using the Android system to deliver search queries and display 786search 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 792href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">action view</a>, and you enable it to 793appear in the Action Bar "if there is room" (by setting {@code 794android:showAsAction="ifRoom"}), then there is a chance that the search widget will not appear 795as an action view, but the menu item will appear in the overflow menu. For example, when your 796application runs on a smaller screen, there might not be enough room in the Action Bar to display 797the search widget along with other action items or navigation elements, so the menu item will 798instead appear in the overflow menu. When placed in the overflow menu, the item works like an 799ordinary 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 802activate the search dialog when the user selects it from the overflow menu. In order for it to do 803so, you must implement {@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} to 804handle the "Search" menu item and open the search dialog by calling {@link 805android.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 808the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action 809Bar</a> developer guide.</p> 810 811<p>Also see the <a 812href="{@docRoot}resources/samples/SearchableDictionary/src/com/example/android/searchabledict/SearchableDictionary.html" 813>Searchable Dictionary</a> for an example implementation using 814both 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 821android:voiceSearchMode} attribute to your searchable configuration. This adds a voice search 822button that launches a voice prompt. When the user 823has finished speaking, the transcribed search query is sent to your searchable 824activity.</p> 825 826<p>For example:</p> 827 828<pre> 829<?xml version="1.0" encoding="utf-8"?> 830<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</searchable> 835</pre> 836 837<p>The value {@code showVoiceSearchButton} is required to enable voice 838search, while the second value, {@code launchRecognizer}, specifies that the voice search button 839should 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 842as the language to be expected and the maximum number of results to return. See the <a 843href="searchable-config.html">Searchable Configuration</a> reference for more information about the 844available attributes.</p> 845 846<p class="note"><strong>Note:</strong> Carefully consider whether voice search is appropriate for 847your application. All searches performed with the voice search button are immediately sent to 848your searchable activity without a chance for the user to review the transcribed query. Sufficiently 849test the voice recognition and ensure that it understands the types of queries that 850the 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 859search suggestions.</p> 860</div> 861 862<p>Both the search dialog and the search widget can provide search suggestions as the user 863types, with assistance from the Android system. The system manages the list of suggestions and 864handles 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 871your application. 872 <p>See <a href="adding-recent-query-suggestions.html">Adding Recent Query 873Suggestions</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 876immediately select the correct spelling or item they are searching for. Figure 3 shows an 877example of custom suggestions for a dictionary application—the user can select a suggestion 878to instantly go to the definition. 879 <p>See <a href="adding-custom-suggestions.html">Adding Custom 880Suggestions</a></p></dd> 881</dl> 882 883