Searchable for Android

Source: Internet
Author: User

Android searchable

I. Preface:

Android provides a unified search interface for the search function of the program, including Search dialog and search widgets.
The Search dialog can only be located above the activity window, and the search widget can be located anywhere.
Both Search dialog and search widget send messages to our searchable activity (mainly for search keywords ).
In this way, you can add Search dialog and search widgets to any activity. The system can start an appropriate activity to process the search and display the results.
Other attributes of Search dialog and search widget are as follows:
A: Sound search.
B: Provide search suggestions based on the latest search results.
C: Provide search suggestions based on the actual search results of our program.
NOTE 1: The Search widget is available in Android 3.0 or later.
NOTE 2: searchable activity actually performs the search.
Ii. Basic Knowledge
Before you start to implement the search function, decide whether to use the Search dialog or the search widget.
Their search features are the same, but they are slightly different.
A. Search dialog is a system-controlled UI component. But when the user is activated, it always appears above the activity, as shown in.
B. The Android system is responsible for handling all the events on the Search dialog. When a user submits a query, the system will transmit the query request to our searchable activity,
Let searchable activity process real queries. When the user inputs the data, the Search dialog can also provide search recommendations.
C. The search widget is an instance of searchview. You can place it anywhere in your layout.
D. By default, the search widget is the same as a standard edittext widget and cannot do anything.
However, you can configure it to allow the Android system to process all key events and transmit query requests to the appropriate activity. You can configure it to provide search suggestions like Search dialog.
E. The search widget is available in Android 3.0 or later. Search dialog does not have this restriction.
Tip: If you want to process all user input in the search widget, use various callback functions and listening interfaces. For details, refer to searchview.
Figure 1:

When you perform a search in Search dialog or search widget, the system creates an intent and stores the query keywords,
Start the searchable activity declared in androidmanifest. xml and send the intent to it.
To implement a program that can be searched, you need the following parts:
(1) the configuration file of Search dialog or widget.
Configure an XML file to configure Search dialog or widget settings. For Search dialog, the configuration file name is generally set to searchable. xml.
(2), searchable activity.
Searchable activity is used to receive search keywords, search data, and display search results.
(3). search results. Search dialog or search widget
* The Search dialog
By default, Search dialog is hidden. When we press the search key or call onsearchrequested () in a program, it will appear above the screen.
* A searchview widget
When using the search widget, you can place the search entry anywhere in our activity.
Instead of putting it in your activity layout, however, it's usually more convenient for users as an action view in the action bar.
3. Create the configuration file searchable. xml
The configuration file describes the attributes of the Search dialog or widget. Includes the UI, suggestions, and Voice Search behave attributes.
This file is generally set to searchable. xml and is located in the Res/XML/directory.
Searchable. xml must use <searchable> element as the root node and define at least one attribute.
For example, Example 1:
<? XML version = "1.0" encoding = "UTF-8"?>
<Searchable xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Label = "@ string/app_label"
Android: hint = "@ string/search_hint">
</Searchable>
Android: label is a unique attribute that must be defined. It points to a string, which should be the name of the application.
In fact, this label is only visible when search suggestions for quick search box is available.
The label is visible in the searchable item list set by the system.
Although the Android: hint attribute is not required, the recommendation always defines it. It is a prompt in the input box before the search box user input.
<Searchable> there are other attributes. If you do not need search suggestions or Voice Search, most of the attributes are not required.

For more information about searchable. XML, see: http://developer.android.com/guide/topics/search/searchable-config.html

Android searchable 2

4. Create a searchable Activity
Searchable activity searches based on search keywords and displays search results.
When we perform a search in the Search dialog or widget, the system starts your searchable activity and transmits the search keyword to your searchable activity using an aciton intent of action_search. your searchable activity uses extra query in intent to extract search keywords, execute the search, and display the search results.
We need to declare searchable activity in the androidmanifest. xml file, so that when the Search dialog or widget executes the search, the system starts the searchable activity and passes the search keyword to it.
4.1 declare searchable Activity
How to declare searchable activity in the androidmanifest. xml file
1. Add an intent that accepts action as action_search in <intent-filter> of the activity.
2. Specify the Search dialog or widget configuration file (searchable. XML) in <meta-data>)
For example, Example 2:
<Application...>
<Activity Android: Name = ". searchableactivity">
<Intent-filter>
<Action Android: Name = "android. Intent. Action. Search"/>
</Intent-filter>
<Meta-data Android: Name = "android. App. searchable"
Android: Resource = "@ XML/searchable"/>
</Activity>
...
</Application>
<Meta-data> the property Android: name must be included, and its value must be "android. App. searchable ",
It must also include the Android: Resource attribute, which specifies the configuration file of our Search dialog. (In example 2, specify the Res/XML/searchable. XML ).
Note: <intent-filter> you do not need to add <category Android: Name = "android. Intent. Category. Default"/>,
Because the system uses component name to pass the display of action_search intent explicitly to searchable activity.
4.2 perform search
When you declare searchable activity in the manifest file, you can perform the search in the following three steps in your searchable activity.
(1), extract search keywords
(2) Search your data
(3) Display Search Results
In general, your search results need to be displayed in listview, and all your searchable activities need to inherit from listactivity.
It includes a layout with a single listview, which provides convenience for us to use listview.
4.2.1 extract search keywords
When you start searching on the Search dialog or widget interface, the system will find a suitable searchable activity and send it an action_search intent, this intent stores the search keywords in the extra query. When the activity is executed, we must check the search keyword saved in the extra query and extract it.
For example, Example 3:
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Search );

// Get the intent, verify the action and get the query
Intent intent = getintent ();
If (intent. action_search.equals (intent. getaction ())){
String query = intent. getstringextra (searchmanager. query );
Domysearch (query );
}
}
In the intent where action is action_search, the extra query is always included. In Example 3, the search keyword is extracted and processed, and then the domysearch () function is executed to perform a real search.
4.2.2. Data Search
Data storage and search are related to your program. You can store and search data in various ways. It is more important for your program.
Note the following points:
(1) When your data is stored in the mobile phone database, execute full-text search (using fts3, rather than a like query)
It provides a more robust and faster search for text data. In sqlite.org, you can get more information about fts3. In sqlitedatabase, you can see more information about SQLite on Android. You can see an example of searching using fts3 in searchable dictionary.
(2) If the data comes from the Internet, your search will be subject to user data connections. In this case, we need to display a progress bar until the search results are returned from the Internet.
. In android.net, you can see more network APIs. in creating a progress dialog, you can see how to display a progress bar.
If you want to make the data and search transparent, I suggest you use an adapter to return the search results. In this way, you can easily Display Search Results in listview. If your data is in the database, you can use cursoradapter to provide the search result to listview. If your data comes from other methods, you can use a baseadapter extension.
4.2.3. Result Display
As discussed above, the UI recommended for displaying search results is listview, so your searchable activity is best inherited from listactivity, and then setlistadapter () to set the adapter bound to the search result. In this way, your search results will be displayed in listview.
You can refer to the searchable dictionary example to show how to perform database queries and how to use the adapter to provide search results to listview.

Android searchable 3

5. Use Search dialog
Search dialog provides a search bar floating above the screen, and the application icon is displayed on the left of the search bar. When you enter a keyword, it provides the suggested search keyword.
When you search by yourself, the system will execute the real search keyword searchable activity.
However, if your device uses Android 3.0 (or later), you can consider using the search widget.
Search dialog is hidden by default until the user activates it. If a search button is displayed on the mobile phone, press this key to activate the Search dialog by default.
To use the Search dialog, you must specify which searchable activity will be requested by the Search dialog to execute the search. For example, in Example 2, it is a searchable activity named searchableactivity. Of course, it also uses the Search dialog. If you want to use other actvitity to display the Search dialog, such as otheractivity, to display the Search dialog and pass the search request to searchableactivity,
You must declare a searchable activity in manifest
(Such as searchableactivity) to receive the Search dialog request in otheractivity.
Declare searchable activity for the Search dialog of an activity. You need to add <meta-data> to the <activity> element of the activity in androidmanifest. xml.
This <meta-data> must contain the "Android: Value" attribute, which specifies the class name of searchable activity,
The property "Android: Name" must also be included, and its value must be "android. App. default_searchable ".
The following example declares two searchable activities (searchableactivity and otheractivity ),
Otheractivity also uses searchableactivity in its search dialog to perform the searches operation.
Example 4:
<Application...>
<! -- This is the searchable activity; it performs searches -->
<Activity Android: Name = ". searchableactivity">
<Intent-filter>
<Action Android: Name = "android. Intent. Action. Search"/>
</Intent-filter>
<Meta-data Android: Name = "android. App. searchable"
Android: Resource = "@ XML/searchable"/>
</Activity>

<! -- This activity enables the Search dialog to initiate searches
In the searchableactivity -->
<Activity Android: Name = ". otheractivity"...>
<! -- Enable the Search dialog to send searches to searchableactivity -->
<Meta-data Android: Name = "android. App. default_searchable"
Android: value = ". searchableactivity"/>
</Activity>
...
</Application>
Because otheractivity already contains a <meta-data> element, it declares which searchable activity is used to perform the search, so its Search dialog becomes available. By pressing the search button (if any) on your phone or calling onsearchrequested (), Search dialog is activated.
Once you perform the search operation in the Search dialog, the system starts searchableactivity and sends action_search intent to it.
Tip: searchable activity provides the Search dialog by default, and Its searchable activity is itself, so it does not need to be declared.

If you want to provide the Search dialog for each activity of your application, add the <meta-data> element to <Application> as its son instead of each <activity>. in this way, each activity inherits this value, provides Search dialog, and transmits searches to the same searchable activity. (If you have multiple searchable activities, you can add different <meta-data> in a single activitiy to declare searchable.
In this way, the default searchable activity is overwritten)

6. How to start search Dialog

As mentioned above, if the current activity declares the use of searchable activity, the Search dialog will be activated by pressing the search button (if any) on the mobile phone or calling onsearchrequested.

However, the Search button is not available on all devices, so you need to provide a search button in your UI,

To activate the Search dialog by calling onsearchrequested.

For example, you can call onsearchrequested () in a menu item in the Options Menu or in the layout button of your activity to start the search dialog.

The search_icons.zip file contains search icons for the medium and high density screens, you can use it in your search menu item or button (low-density screens scale-down the hdpi image by one half ).

You can also use the "type-to-search" function. In this way, when you input data on the keyboard, the Search dialog is activated and directly entered into the Search dialog.

You can call setdefakeykeymode (default_keys_search_local) in oncreate () of activity to enable this function.

Android searchable 4

7. Impact of Search dialog on activity Lifecycle
The Search dialog is just a dialog floating on the screen. It does not cause any changes to the activity stack. Therefore, when the Search dialog is started, no lifecycle functions (such as onpause () are transferred ()). Your activity only loses the input focus because the input focus is transferred to the Search dialog.
If you want to be notified when you start Search dialog, rewrite the onsearchrequested () method of the activity.
When the system calls this method, it means that your activity has lost the input focus and the input focus has been transferred to the Search dialog, so you can do something related to your work (such as suspending the game) here ). at the end of onsearchrequested, you can call onsearchrequested of the parent class.
Example 4:
@ Override public Boolean onsearchrequested (){
Pausesomestuff ();
Return super. onsearchrequested ();
}
If you cancel the search by pressing the back key, the Search dialog is disabled and your activity gets the input focus again. You can use setondismisslistener ()/setoncancellistener () to register the listener ondismisslistener/oncancellistener to listen for the closure of Search dialog. When Search dialog is disabled, ondismisslistener will be called. Oncancellistener is called only when the user explicitly exits the search Diener. It is not called when the user executes the search (in this case, the user disappears naturally and does not cancel it ).
If the current activity is not the searchable activity we specified, the normal activity lifecycle event will be triggered when the user executes the search.
(It will call onpause () and be paused). However, if it is currently the searchable activity specified by current activity, the following two things will happen:
A. By default, searchable activity will call oncreate () to respond to the action_search intent, and a new instance of this activity will be placed in the activity stack. At this time, your searchable activity has two instances in the activity stack (if you press the back key, it will return to the previous searchable activity instance,

Instead of leaving searchable activity ).
B. if you set the Android: launchmode attribute of searchable activity to "singletop", searchable activity calls onnewintent (intent) to respond to this action_search, at the same time, action_search intent is also passed in here. the example 5 below is a good example of how to deal with searchable activity when the launch mode is "singletop.
Example 5:

@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Search );
Handleintent (getintent ());
}

@ Override
Protected void onnewintent (intent ){
Setintent (intent );
Handleintent (intent );
}

Private void handleintent (intent ){
If (intent. action_search.equals (intent. getaction ())){
String query = intent. getstringextra (searchmanager. query );
Domysearch (query );
}
}

All the processing of search intent is placed in the handleintent () function, so you can directly call it in oncreate () and onnewintent.

When the system calls onnewintent (intent), it indicates that the activity is not newly created, so the intent received in oncreate () is returned by getintent. therefore, you must call setintent (intent) in onnewintent (intent) (in this way, the saved intent will be updated, and then you can get it through getintent ).

Using "singletop" is a common method, because once a user executes a search, it often wants to execute a search, and it is not good to create a large number of searchable activities. Therefore, we recommend that you set all searchable activities to the "singletop" Mode in manifest.

Example 6
<Activity Android: Name = ". searchableactivity"
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>:

8. send data to searchable Activity

Sometimes, you may want to add more content based on the search keyword received by the searchable activity. However, sometimes the added content depends on the activity that starts the Search dialog. Anroid allows you to add your data to the intent sent by the system to searchable activity. Action_search intent carries your data by carrying a bundle named app_data. To transmit your data, repeat onsearchrequested () in the acitivity of the search request, create a bundle, and put the data you want to carry in it, call startsearch () to activate search using bundle as one of the parameters.
Dialog.

For example, Example 7:

@ Override
Public Boolean onsearchrequested (){
Bundle appdata = new bundle ();
Appdata. putboolean (searchableactivity. jargon, true );
Startsearch (null, false, appdata, false );
Return true;
}

If "true" is returned, the callback event has been successfully processed. You can call startsearch () to activate the Search dialog. once the user submits a search request, it will be transmitted to the searchable activity like the data you added. You can use app_data bundle to extract it.

Example 8:

Bundle appdata = getintent (). getbundleextra (searchmanager. app_data );
If (appdata! = NULL ){
Boolean jargon = appdata. getboolean (searchableactivity. jargon );
}

Note: Do not call it outside onsearchrequested ()
Startsearch () method. When you need to activate Search dialog in your activity, always onsearchrequested (). otherwise, if onsearchrequested () is not called, some personalized operations cannot be executed (for example, adding additional data in the preceding example)

Android searchable 5 (use search widget)

9. Use the search widget

In Android 3.0 or later, you can use the searchview widget. if your program is based on anroid3.0 and you plan to use the search widget, we recommend that you use the search widget as an action view in the action bar, instead of using Search dialog (do not place the search widget in your activity layout ). for example, Figure 2 uses the search widget as an action bar.

The search widget provides the same functions as Search dialog. When a user executes a search, it starts a suitable activity for processing. It also provides search keyword recommendations and language searches.

Note: When you use the search widget as the action view, you may still need to use the Search dialog. For example, sometimes the search widg is not suitable in the action bar. for details, refer to "use both the search widget and Search dialog" below.

Figure 2:

10. Configure the search widget

First, you should first create the searchable configuration and searchable activity, and then set the search assistant for each searchview. You can use setsearchableinfo () to set your searchableinfo object. searchableinfo indicates your searchable configuration.

You can get a reference of searchableinfo through getsearchableinfo () of searchmanager.

For example, if you want to use searchview as an action view in the action bar, enable the widget instance 10 in the callback number oncreateoptionsmenu:

@ Override
Public Boolean oncreateoptionsmenu (menu ){
// Inflate the Options menu from XML
Menuinflater Inflater = getmenuinflater ();
Inflater. Inflate (R. Menu. options_menu, menu );

// Get the searchview and set the searchable Configuration
Searchmanager = (searchmanager) getsystemservice (context. search_service );
Searchview = (searchview) menu. finditem (R. Id. menu_search). getactionview ();
Searchview. setsearchableinfo (searchmanager. getsearchableinfo (getcomponentname ()));
Searchview. seticonifiedbydefault (false); // do not iconify the widget; expand it by default,
Return true;
}
Now that the search widget is configured, the system can send the SEARCH Command to your searchable activity. You can also use search suggestions in the search widget.
Note: If you want to process all user input by yourself, process it in its callback function and event listening interface method. For more information about searchview and its listening interfaces, refer to the searchview documentation.
For more information about the action views in the action bar, see using the action bar (which contains the instance code to add the search widget as the action view)
11. Other features of the search widget

You can add some other features to searchview.

A. submit button (a submit button)
By default, no search button is submitted, so you must press "return" on the keyboard to submit the search. you can use setsubmitbuttonenabled (true) to add a submit button ("Submit" button)
Note: The "return" key here should be the "enter" key.
B. Custom Search suggestions
When you use search suggestions, you often want users to simply select suggestion, but they may also want to customize suggested search query. you can call setqueryrefinementenabled (true) to add a button for each suggestion so that users can enter the custom suggestion in the search box.
C. For details about search box, see
By default, the search widget is "iconified" and is represented by an icon (a magnifier). The search box is displayed only when you press it. you can call seticonifiedbydefault (false) to display search boxes by default. You can also call seticonified () to display it as iconified.

There are other APIs in searchview that allow you to personalize the display of search widgets. However, most of them are used when you process user input, not when Android system processes the input and display of search suggestions.

12. Use both the search widget and Search dialog
If you insert the search widget into the action bar as the action view, you can make it appear in the action bar only when there is sufficient space (by setting Android: showasaction = "ifroom"), then the search widget may not appear in the form of action view, but in the form of menu in the overflow menu. for example, if your program runs on a cell phone on a small screen, there is not enough space in the action bar to search widgets and other actions items or navigation
Elements. They will appear in the overflow menu as menu items. when displayed in the overflow menu, this item is like a normal menu item and it no longer displays the action view (the search widget ).
To handle this problem, you must activate the Search dialog when you select the menu item associated with the search widget. To handle this, you must process the "Search" menu item in onoptionsitemselected () h and enable the Search dialog by calling onsearchrequested.

For more information about how the action bar works and processes the situation, see using the actionbar. You can also refer to the Search dialog and search widget instance searchable dictionary.

Android searchable 6 (voice search and search suggestions)

13th, Voice Search)
You can add the Android: voicesearchmode attribute in your searchable configuration to add the Search dialog or widget language function.
In this way, a button is added to start Voice Search for voice prompt. Once the user completes speaking, the transcribed search query will be sent to your searchable activity.
Example 11:
<? XML version = "1.0" encoding = "UTF-8"?>
<Searchable xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Label = "@ string/search_label"
Android: hint = "@ string/search_hint"
Android: voicesearchmode = "showvoicesearchbutton | launchrecognizer">
</Searchable>
The first value "showvoicesearchbutton" is used to enable voice search. The second value "launchrecognizer" indicates that the Voice Search button should start a recognizer to pass transcribed text to your searchable activity.
You can also use other attributes to define the voice search behavior, such as the language and the maximum number of returned results.
For more voice search attributes, refer to searchable configuration.
Note: Please carefully consider whether you want to use Voice Search in your program. all searches via the Voice Search button are directly sent to your searchable activity, and you have no chance to preview transcribed query. Voice recognition needs to be fully tested so that it can identify various requests submitted by users in your program.

14. Search suggestions
Both the Search dialog and the search widget can provide recommended search terms when searching with the help of the Android system.
The system manages the suggestions list and processes the suggestion event selected by the user.
Generally, you can provide the following two recommended search terms:
Recent search term:
These search words are just some of your previous search keywords. For more information, see Adding recent query suggestions.
Personalized search term:
These search suggestions all come from your own data, which helps users quickly select the correct spelling or the items they want to search.
Figure 3 is a customized suggestions interface of the dictionary Program-you can select a suggestion to quickly get its definition. For more information, see adding custom suggestions
Figure 3:

Address: http://www.fengfly.com/plus/view-206556-1.html

From: http://www.fengfly.com/plus/view-206551-1.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.