Use of the Android floating search box

Source: Internet
Author: User


We often need to provide search services in our applications, such as searching for contacts, searching for product information, and so on. We can customize our search box in our layouts to implement our search logic. But there is an easier way: Use the Android system to provide us with the search function framework.
In Android, there are two ways to implement the search function: Searching dialog and Searchview.
Search dialog is similar to normal dialog, hovering over our form. The example diagram is as follows:

Searchview are often nested in our layouts, and the most typical case is the use of Searchview in Actionbar. Is the use of searchview in. (PS: The magnifying glass in the figure is Searchview)

Regardless of which method you use, the Android system sends query requests to the activity that processes the search logic to implement the search function.
In addition, in addition to ordinary text search, but also provides a bit of search function:
1. Voice Search
2. Recent Search Record Tips
3. Custom Search Record Tips System Search Box

Google System search box

It is important to note that the Android system does not provide search logic, which means that when the system passes the search keyword to us, we need to handle the search logic ourselves. For example, search in the database, search the network.
In addition, the Android system does not explicitly call our search box, we need to call the method to display our search box.
Today we mainly introduce how search dialog is used.

Basic principle

First, let's look at the fundamentals of the system search function.
(a) When the user performs a search in the search box, a intent is automatically created and the keywords that are searched by the user are stored in the intent.
(ii) The system initiates activity that processes the search logic (which can typically be named searchableactivity) and passes intent to searchableactivity, We then process our search logic in searchableactivity.

Configure the search box

In the first step, we need to configure the XML file for our search box, which includes attributes such as voice search, search hints, search history, and so on.
The configuration file is usually named Searchable.xml and must be stored in the Res/xml directory of our project (no one is created)
(PS: The system uses this configuration file to instantiate the Searchableinfo object, which provides search-related metadata, such as the Searchableactivity class name, the type of search keyword, and so on. But we can't instantiate the Searchableinfo object ourselves, only through configuration files.
The following is the contents of the Searchable.xml configuration file


<?xml version="1.0" encoding="utf-8"?><searchable xmlns:android=""    android:hint="@string/searchHint"    android:label="@string/searchLabel" ></searchable>

The root node of the configuration file must be searchable, where label is required, and its value is a string resource reference, usually the name of the application (although it is a required property, it is usually not displayed unless you turn on the search suggestions feature).
Android:hint is the input prompt to configure the search box, although it is not a required property, it is strongly recommended to set this property so that users can enter search information when they are able to enter the search information.
To configure many properties, but most of the properties are only configured when using search suggestions and voice searches.


In the second step, we create searchableactivity to process the search logic and display the search results.
We need to configure some properties of searchableactivity in the Android-manifest.xml file to designate it as activity to process the search logic


... >    <activity android:name=".SearchableActivity" >        <intent-filter>            <action android:name="android.intent.action.SEARCH" />        </intent-filter>        <meta-data android:name=""                   android:resource="@xml/searchable"/>    </activity>    ...</application>

First add the Action_search ACTION to the Intent-filter node. Then the Name property in the Meta-data node must be the,resource property for our configuration file Searchable.xml
Note: We do not need to configure the category in Intent-filter because Searchmanager will pass the data to it according to the componentname of searchableactivity.
Look at the following Searchmanager.class source code, we can know how this is achieved.


 /** * Starts the global search activity. */    / * Package * / voidStartglobalsearch (String initialquery,BooleanSelectinitialquery, Bundle appsearchdata, Rect sourcebounds) {//This is our searchableactivity.ComponentName globalsearchactivity = getglobalsearchactivity ();if(Globalsearchactivity = =NULL) {LOG.W (TAG,"No Global search activity found.");return; } Intent Intent =NewIntent (Intent_action_global_search); Intent.addflags (Intent.flag_activity_new_task);//Display deliveryIntent.setcomponent (globalsearchactivity);//Make sure and we have a Bundle to put source in        if(Appsearchdata = =NULL) {Appsearchdata =NewBundle (); }Else{Appsearchdata =NewBundle (Appsearchdata); }//Set Source to package name of app this starts global search, if not set already.        if(!appsearchdata.containskey ("Source") {appsearchdata.putstring ("Source", Mcontext.getpackagename ()); }//Query dataIntent.putextra (App_Data, appsearchdata);if(!        Textutils.isempty (Initialquery)) {Intent.putextra (QUERY, initialquery); }if(Selectinitialquery)        {Intent.putextra (extra_select_query, selectinitialquery); } intent.setsourcebounds (Sourcebounds);Try{if(DBG) LOG.D (TAG,"Starting Global Search:"+ Intent.touri (0));        Mcontext.startactivity (Intent); }Catch(Activitynotfoundexception ex) {LOG.E (TAG,"Global Search activity not found:"+ globalsearchactivity); }    }

In general, the data that is queried is shown through a ListView, so we can let searchableactivity inherit listactivity for ease of operation.

In searchableactivity, we need to complete three things:
1. Accept Query Parameters
When the user performs the search operation, the system passes the data named query through intent, which contains our search keywords, we can accept the query data in the intent

 Public  class searchactivity extends listactivity{            //test Data    PrivateString[][] Datas = {{"Activity","Actionbar","Animation","Android"},            {"Bundle","Block","Bluetooth","Boolean"} };//Query Results    PrivateString[] result;PrivateIntent Intent;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_search); Intent = getintent ();//Determine if it is a search request        if(Intent.ACTION_SEARCH.equals (Intent.getaction ())) {//Get search query Content (keywords)String query = Intent.getstringextra (searchmanager.query);

2. Query data based on query parameters

Once we get to query keyword, we can execute our query logic.

    // 执行相应的查询动作            boolean isSuccess =queryContact(query);
privatebooleanqueryContact(String query)    {        for (String[] ss : datas)        {            for (String s : ss)            {                if (s.contains(query)){                    result = ss;                    returntrue;                }            }        }        returnfalse;    }

The Querycontact method is the way I write a mock query dictionary. This can be replaced by querying data in a database or network.

3. Display the queried data
In the query to the data, we need to display the data in the ListView, and when the user clicks on a query result, the query results are returned to mainactivity.

Intent =NewIntent (searchactivity. This, Mainactivity.class);if(issuccess) {Setlistadapter (NewArrayadapter<> ( ThisAndroid.                R.layout.simple_list_item_1, result)); Getlistview (). Setonitemclicklistener (NewOnitemclicklistener () {@Override                     Public void Onitemclick(adapterview<?> parent, view view,intPositionLongID) {Intent.putextra ("Name", Result[position]);                    StartActivity (Intent);            }                }); }Else{Toast.maketext ( This,"No query to Data", Toast.length_short). Show ();            StartActivity (Intent); }        }    }
Use the search box

Finally, we need to use our search box in mainactivity. As I said earlier, the search box is hidden by default and needs to be called by ourselves. Before calling, we also need to configure in the manifest file to specify the use of searchableactivity.

  <activityandroid:name=". Mainactivity "android:label=" @string/app_name " >                                        <!--enable the search dialog to send searches to searchableactivity -        <meta-data android:name=""android:value =". Searchactivity " />                               <intent-filter>                <action android:name="Android.intent.action.MAIN" />                <category android:name="Android.intent.category.LAUNCHER" />            </intent-filter>        </activity>

In the Mianactivity node, we need to configure the Meta-data node, and name must be specified as,value to represent our searchableactivity.
If you want to specify the search box as global and can be used throughout the application, configure the Meta-data node in the application node.

Finally, we call the search box in mainactivity.
Because the physical keys of different devices vary greatly, some phones have physical search keys, and some phones are not. So we'd better have a search button in the activity to explicitly call the search box. Another way is to call the search box via the search button on the phone's soft keyboard, which requires calling Setdefaultkeymode (default_keys_search_local) in OnCreate ().
The search box is a dialog that floats on the screen. It does not cause any changes to the activity stack and life cycle. So when the search box appears, no method like OnPause () is called.
By calling the Onsearchrequested () method, we activate the search box.
In Mainactivity, we click on the button to display the search box, and after the search is performed, the obtained search results are displayed in TextView.


 Public  class mainactivity extends actionbaractivity{    PrivateTextView msg;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);    Msg= (TextView) Findviewbyid (; }@Override    protected void Onresume() {String name = (string) getintent (). Getstringextra ("Name");if(name!=NULL) msg.settext (name);Super. Onresume (); } Public void Search(View view)    {onsearchrequested (); }}

Alternatively, we can rewrite the onsearchrequested () method to do some other things while searching, such as pausing music playback and so on.

@OverridepublicbooleanonSearchRequested() {    pauseMusic();    returnsuper.onSearchRequested();}

Also, if we need to impose some restrictions on the query keyword, we can call onsearchrequested () to send some extra data to the searchableactivity,searchableactivity for processing.

@OverridepublicbooleanonSearchRequested() {//查询参数     new Bundle();     true);     startSearch(nullfalsefalse);     returntrue; }

When searchableactivity receives the query parameters and keywords that are passed, the query operation can be performed.

//通过SearchManager.APP_DATA来提取数据Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA);if (appData != null) {    boolean jargon = appData.getBoolean(SearchableActivity.JARGON);  //下面这一句表示我们可以进行的操作。。。。  ......=jargon”;}

Note: We can no longer onsearchrequested () method calls with the Startsearch method, and any operation must be called through onsearchrequested ().

This article is referenced from the Android website:

Source Download

Use of the Android floating search box

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.