My android advanced tour --> Android uses autocompletetextview to Display Search history prompts

Source: Internet
Author: User

Introduction

Google or Baidu is often used when we access the internet. If we enter the information we want in the input box, other prompts related to it will appear, which is very convenient. This effect is implemented using autocompletetextview in Android, and autocompletetextview is an editable text view. When you type it, the suggestion information is displayed automatically.

The suggestion list is displayed in the drop-down list box. You can select an item to replace the content in the edit box.

When you click Enter or click Enter, the drop-down list automatically disappears.

The recommended list is the data obtained from a data adapter.

Step 1: Create a project AutoComplete

Step 2: design the application UI/layout/Main. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <! -- When there is an edittext or autocompletetextview, the focus is obtained by default when you enter the screen. To remove focus, add an O-pixel layout before auto and set it to get focus first. --> <Linearlayout Android: layout_width = "0px" Android: layout_height = "0px" Android: focusable = "true" Android: focusableintouchmode = "true"> </linearlayout> <! -- Define an Automatic completion text box, specify a character to input and prompt --> <autocompletetextview Android: Id = "@ + ID/auto" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: hint = "Enter Text to search" Android: completionhint = "The Last Five Records" Android: dropdownhorizontaloffset = "20dp" Android: completionthreshold = "1" Android: dropdownheight = "fill_parent"/> <! -- Android: completionhint: The title displayed in the drop-down menu. Android: completionthreshold: specifies the number of characters that the user must enter to display the Android: dropdownhorizontaloffset prompt. By default, the drop-down menu is left aligned with the text box. Android: dropdownverticaloffset sets the vertical offset between the drop-down menu and text box. The drop-down menu is followed by the text box Android: dropdownheight by default. Set the height of the drop-down menu. Android: dropdownwidth sets the width of the drop-down menu --> <button Android: text = "Search" Android: id = "@ + ID/search" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"/> </linearlayout>

Step 3: mainactivity. Java

Package CN. roco. autoComplete; import android. app. activity; import android. content. sharedpreferences; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. view. view. onfocuschangelistener; import android. widget. arrayadapter; import android. widget. autocompletetextview; import android. widget. button; public class mainactivity extends activity {private autoco Mpletetextview autocompletetextview; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); autocompletetextview = (autocompletetextview) findviewbyid (R. id. auto); initautocomplete ("History", autocompletetextview); button searchbutton = (button) findviewbyid (R. id. search); searchbutton. setonclicklistener (New myonclicklistener ();} privat E final class myonclicklistener implements onclicklistener {@ overridepublic void onclick (view v) {savehistory ("History", autocompletetextview );}} /*** Save the content in the specified autocompletetextview to the specified character segment in sharedpreference ** @ Param field * The field name in the sharedpreference * @ Param autocompletetextview * The autocompletetextview */private void savehistory (string field, autocompletetextview) {string text = Autocompletetextview. gettext (). tostring (); sharedpreferences sp = getsharedpreferences ("network_url", 0); string longhistory = sp. getstring (field, "nothing"); If (! Longhistory. contains (Text + ",") {stringbuilder sb = new stringbuilder (longhistory); sb. insert (0, text + ","); SP. edit (). putstring ("History", sb. tostring ()). commit () ;}/ *** initialize autocompletetextview. A maximum of five prompts are displayed, the autocompletetextview automatically prompts ** @ Param field * field name saved in sharedpreference * @ Param autocompletetextview */private void initautocomplete (string field, autocompletetextview) {sharedpreferences sp = getsharedpreferences ("network_url", 0); string longhistory = sp. getstring ("History", "nothing"); string [] histories = longhistory. split (","); arrayadapter <string> adapter = new arrayadapter <string> (this, android. r. layout. simple_dropdown_item_1line, histories); // only keep the latest 50 records if (histories. length> 50) {string [] newhistories = new string [50]; system. arraycopy (histories, 0, newhistories, 0, 50); adapter = new arrayadapter <string> (this, android. r. layout. simple_dropdown_item_1line, newhistories);} autocompletetextview. setadapter (adapter); autocompletetextview. setonfocuschangelistener (New onfocuschangelistener () {@ overridepublic void onfocuschange (view V, Boolean hasfocus) {autocompletetextview = (autocompletetextview) V; If (hasfocus) {view. showdropdown ();}}});}}

Step 4: deploy the application to the simulator

Step 5: Enter the application several times, click the search button to save the history, exit the application, and then enter the application again.

Step 6: Search again at this time will have the effect of Automatic completion:

Note:

If you are familiar with Android list development, you should be very familiar with the adapter. The above instance Code uses the arrayadapter provided by Android to bind the data and view to autocompletetextview. We need to customize it first.

 

Like other adapers, the base class of arrayadapter is also a baseadapter. We can customize our own adapter.


 

But when there was a run, there was a response from wood, and there was no prompt?

 

Indeed, our views and data are bound, but autocompletetextview cannot obtain suitable data based on our adapter, because the adapter does not meet the requirements!

 

In turn, we will study arrayadapter, which is not only a sub-class of baseadapter, but also implementsFilterableInterface!

 

In autoadapter, we implement this interface and return a customFilter

 

 

What kind of class does automailfilter look like?

 

First, let's take a closer look at how autocompletetextview works. Right, it only filters and indexes some of the characters we enter and forms a view to feedback to our users, to improve our input efficiency!

 

The next step is to build the core filter. autocompletetextview will only receive the filtered data, so we will copy one more copy of the data source, one original copy, one copy is filtered:

 

 

In automailfilter, we must implement two important methods due to inheritance:

 

Protected filterresults extends mfiltering (charsequence prefix)

In this method, you can customize a filtering policy to filter data based on the input prefix and assemble the data into filterresults results to return the results;

 

Protected void publishresults (charsequence constraint, filterresults results)

This method is used for publishing results. After the results of the above method are processed according to certain requirements, the adapter is notified to refresh the data view.

 

Summary:

 

According to the workflow of autocompletetextview, it depends on two components: adapter and filter. One is view processing, and the other is data filtering processing, which is deeply customized, we can do what we want.

========================================================== ========================================================== ============================

Author: Ouyang Peng: Welcome to repost. sharing with others is the source of progress!

Reprinted Please retain the original address: http://blog.csdn.net/ouyang_peng

========================================================== ========================================================== ============================

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.