When you need to provide the search service in your application, by using the Android search framework, the application will display a Custom Search dialog box to process users' search requests. By using a simple search button or calling an API from your application, the Search dialog box is displayed at the top of the screen and the application icon is automatically displayed.
This article will teach you how to provide a Custom Search dialog box for your application. In this way, you can provide users with a standardized search experience and add functions such as voice search and search recommendations.
Basic knowledge
The search framework of Android is used for the Search dialog box you manage. You do not need to develop a search box by yourself, and do not need to worry about the location of the search box, you do not need to worry about the impact of the search box on your current interface. All these tasks are handled by the searchmanager class for you (hereinafter referred to as "Search manager"). It manages the entire lifecycle of the android Search dialog box, then, execute the search request that your application will send and return the corresponding search keyword.
When a user executes a search, the search Manager uses a specialized intent to send the search keyword to the activity configured in the configuration file to process the search result. In essence, all you need is an activity to receive intent, then perform the search and give the result. Specifically, what you need to do includes the following:
One search Configuration
We use an xml configuration file to configure the Search dialog box, including some function configuration, such as text box, set the prompt text displayed in the voice search and search suggestion.
An activity used to process search requests
This activity is used to receive the search and query content, and then search your data and display the search results.
A way for users to perform searches
By default, once you configure a searchable activity, the device search key (if any) will call the Search dialog box. However, you should always provide another method for users to call the Search dialog box, such as the search button in the option menu or the button on other user interfaces, because not all devices provide a dedicated search key.
Create a Search dialog box configuration file
The search box configuration file is an XML file used to configure the settings of the search box in your application. This file is generally named searchable. XML, which must be saved in the Res/XML/directory of the project.
The root node of the configuration file must be one or more attributes. As follows:
<?xml version="1.0" encoding="utf-8"?><searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/searchLabel" android:hint="@string/searchHint"></searchable>
In the preceding configuration file, except for the Android: hint attribute, all other configuration items are required in a Search dialog box. Android: label is a required attribute and its value is a string resource reference, A string cannot be used directly. It is usually the name of an application (although it is a required attribute, it is usually not displayed unless you have enabled the search suggestion function ). Android: hint is the input prompt for configuring the search box. It must also reference the string resource configured in string. xml. Strings cannot be used directly.
Many attributes can be configured, but most attributes are configured only when you use search recommendations and Voice Search. However, we recommend that you configure Android: hint, the information to be entered.
Next, you need to put this configuration file in your application.
Create an activity for search
When a user performs a search from a search box, the search manager sends the content (keyword) to be searched to an executable search activity through action_search intent. This acitivity queries the data and displays the result.
Define a searchable Activity
If you are not ready, create an activity for executing the search, declare that it can respond to action_search intent, and add search box configuration information. To do this, you need to add an element and a node of the element in your manifest file. As follows:
<application ... > <activity android:name=".MySearchableActivity" > <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> </activity> ...</application>
The value of Android: name must be "android. app. searchable ", Android: The resource property value must reference the search configuration file (RES/XML/searchable in this example) in the Res/XML/directory mentioned above. XML ).
Note that only the activity node configured with the above meta-data node can perform a search. If you want to call the search box throughout the application, you can perform the following Configuration:
<Application...> <activity Android: Name = ". mysearchableactivity "> <intent-filter> <action Android: Name =" android. intent. action. search "/> </intent-filter> <meta-data Android: Name =" android. app. searchable "Android: Resource =" @ XML/searchable "/> </activity> <activity Android: Name = ". anotheractivity "...> </activity> <! -This configuration allows you to call the search box in the entire application --> <meta-data Android: Name = "android. app. default_searchable "Android: value = ". mysearchableactivity "/>... </Application>
In the above Code, Android: Name = "android. App. default_searchable" defines the name of a search request in the response search box. Android: value specifies the activity that responds to the request and executes the search. When we execute a search request in otheracitivity in the application, mysearchableactivity will be loaded for executing the search and displaying the search results.
Execute a search
When an activity is declared as searchable, the actual search involves three steps: receiving queries, retrieving your data, and submitting results.
Generally, your search results need to be displayed in a listview, so the acitivity you use to perform the search must inherit the listactivity, so that you can easily access the listview API.
Receive search queries
When you perform a search in the Search dialog box, the configured acitivity that can be used for the search will be activated by intent, with some search-related parameters. You need to check the intent and make a search response, as follows:
@ Overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. search); intent = getintent (); // determines whether the search request is if (intent. action_search.equals (intent. getaction () {// obtain the search content (keyword) string query = intent. getstringextra (searchmanager. query); // execute the corresponding query action domysearch (query );}}
The domysearch () method queries the Database Based on keywords or data from the network. If it is a time-consuming search, you also need to use a progress bar to tell the user that the search is in progress, after the final result is returned, you can call the setadapter () method of listview to display the result in listview.
Call the Search dialog box
You can call the onsearchrequested () method from any place in the application to activate the search box, such as a menu or a button. You also need to call setdefakeykeymode (default_keys_search_local) in the oncreate () method. In this way, when you press the key on the keyboard, the search box is automatically activated.
The search box is the same as a normal dialog box. It floats at the top of the screen and does not change the status of any activity stack. No methods in the activity life cycle will be called, but when the search box appears, A running activity will lose the input focus.
If you want to perform other operations during the search, you can rewrite the onsearchrequested () method as follows:
@ Overridepublic Boolean onsearchrequested () {// do what you want in this method, for example, do something that has been first processed as pausesomestuff (); return Super. onsearchrequested ();}
If the current activity is the activity that responds to the search request, there are two situations:
By default, action_search intent will create a new activity and call the oncreate () method. This new activity will display at the beginning, and you will have two activity instances at the same time. When you press the "return" Key, an activity before the search is not executed will be returned.
Another scenario is the activity with Android: launchmode = "singletop" configured. In this case, we need to process the search request in the onnewintent (intent) method, as shown below:
@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); handleIntent(getIntent());} @Overrideprotected void onNewIntent(Intent intent) { setIntent(intent); handleIntent(intent);} private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); doMySearch(query); }}
The corresponding activity configuration is as follows:
<activity android:name=".MySearchableActivity" android:launchMode="singleTop" > <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> </activity>
How to add parameters to the search box
To pass parameters to the search box, we need to override the onsearchrequested () method, as shown below:
@Overridepublic boolean onSearchRequested() { Bundle appData = new Bundle(); appData.putBoolean(MySearchableActivity.JARGON, true); startSearch(null, false, appData, false); return true; }
When receiving a search request from the search box, our activity obtains the parameters as follows:
Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA); if (appData != null) { boolean jargon = appData.getBoolean(MySearchableActivity.JARGON); }
Finally, let's take a look at how to use Android Voice Search:
You only need to make the following changes to our search configuration file. Your search supports voice search. The configuration file is as follows:
<?xml version="1.0" encoding="utf-8"?><searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/searchLabel" android:hint="@string/searchHint" android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"></searchable>