Android uses Autocompletetextview to implement search history tips

Source: Internet
Author: User

  • Introduction   We usually use Google or Baidu when we are on the Internet, it is very convenient to enter the information we want to enter in the input box and other related information. This effect is implemented in Android using Autocompletetextview, Autocompletetextview is a text view that can be edited, and when the user types, the completion suggestions are automatically displayed. The   Suggestions list appears in the drop-down list box, and you can select an item instead of the edit box.   When the user clicks the ENTER key, or nothing is selected click Enter to build the drop-down list will disappear automatically. The   recommendations list is the data obtained from a data adapter. &NBSP;&NBSP;STEP1: Create a new project AutoCompletestep2: UI interface for designing apps  /layout/main.xml[html]  <?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 a edittext or autocompletetextview, it is the default to get the focus when entering the screen.            To remove focus, you can add an O-pixel layout before auto and set him to get focus first. -     <linearlayout android:layout_width= "0px"            Android: layout_height= "0px" android:focusable= "TruE "           android:focusableintouchmode=" true "></LinearLayout>               <!--define an auto-complete text box that specifies a character to prompt with--     < Autocompletetextview            android:id= "@+id/auto"          an Droid:layout_width= "Fill_parent"           android:layout_height= "Wrap_content"            android:hint= "Please enter text to search"          android:completionhint= " Latest 5 Records "         android:dropdownhorizontaloffset=" 20DP "         android:completionthreshold= "1"          android:dropdownheight= "fill_parent"/>                     <!--          Androi D:completionhint             settings appear in the drop-down menuDisplay title          android:completionthreshold       Set the user to enter at least how many characters to show a hint    & nbsp     Android:dropdownhorizontaloffset   Set the horizontal offset between the drop-down menu and the text box. The drop-down menu defaults to the text box left-aligned          Android:dropdownverticaloffset     Sets the vertical offset between the drop-down menu and the text box. The drop-down menu is immediately followed by the text box          android:dropdownheight               Setup dropdown Menu Height          android:dropdownwidth                 set down La carte Single width         --      <button android:text= "search" android:id= "@+id/ Search            android:layout_width= "wrap_content"          &N Bsp android:layout_height= "Wrap_content"/>     </LinearLayout>    step3: Mainactivity.java[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 Autocompletetextview Autocompletetextview;        @Override      public void onCreate (Bundle savedinstancestate) { & nbsp       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 ());             Private Final class Myonclicklistener implements Onclicklistener {& nbsp;        @Override          public void OnClick (View v) {   &n Bsp         savehistory ("History", Autocompletetextview);         }     }       /**      * Specifies that the contents of Autocompletetextview are saved to the specified character segment in sharedpreference       *       * @param field      *             save field names in Sharedpreference      & nbsp;* @param autocompletetextview      *             autocompletetextview      */     private void SA to operateVehistory (String field,              Autocompletetextview Autocompletetextview) {&nbs p;        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 ();         }     }       /**      * Start Autocompletetextview, display up to 5 hints, make Autocompletetextview auto-prompt when starting to get focus       *       * @param field      *             save field names in Sharedpreference        * @param autocompletetextview      *             To operate autocompletetextview      */     private void Initautocomplete (String field, & nbsp;            Autocompletetextview Autocompletetextview) {       &NB Sp 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);         //Keep only the latest 50 records        &nbsp if (Histories.length >) {             string[] newhistories = new STRING[50]; &n bsp;            system.arraycopy (histories, 0, newhistories, 0, 50);              adapter = new Arrayadapter<string> (this,                      Android. R.layout.simple_dropdown_item_1line, newhistories);         }          Autocompletetextview.setadapter (adapter);          Autocompletetextview                  SetO Nfocuschangelistener (New Onfocuschangelistener () {                   &N Bsp @Override                      public void Onfocuschange (View V, bo Olean hasfocus) {                        Autocompletetextview view = (Autocompletetextview) v;                          if (hasfocus) {   &NB Sp                         View.showdropdown ();                         }        &NB Sp            }               / });     }   &NBSP;&NBSP;STEP4: Deploy app to emulator STEP5: After several entries and clicking the Search button to save history, exit the app and re-enter the app Step6: This time, the search will have an auto-complete effect:              Note:  familiar with Android list development, for adapter should be very familiar with the above example code, using the Android provided arrayadapter, give Autocompletetextview bound data and views , we want to customize, start here first.   Like other adaper, Arrayadapter's base class is also baseadapter, and we can customize our own adapter.    but a run, the wood reacts, without a hint?   Indeed, our views and data are bound, but Autocompletetextview can not get the right data according to our adapter, because adapter does not meet the requirements!   We'll look at the arrayadapter in turn, it's a subclass of Baseadapter, it also implements the Filterable interface!   We implement the interface in Autoadapter and return a custom filter   what kind of class is that automailfilter?   Think about how Autocompletetextview works, yes, it's just some of the characters we enter, filter, index, and make up the corresponding view feedback to our users to improve our input efficiency!   The next step is to build the core filter, Autocompletetextview will only receive filtered data, so our data source will have a copy, one copy is original, one is filtered:   In Automailfilter, due to inheritance, we must implement two important methods:  protected filterresults performfiltering (charsequence prefix)   In this method, a custom filtering strategy is used to filter the data according to the input prefix and assemble the filterresults results to return;  protected void Publishresults (charsequence Constraint, filterresults results)   This method is used to publish results, the results of the above method according to certain requirements for processing, notify adapter to refresh the Data View   summary:  in accordance with Autocompletetextview's workProcess, it relies on two components, Adapter and filter, one is the processing of the view, one is the data filtering processing, the two components in depth customization, we can do whatever we want.

Android uses Autocompletetextview to implement search history tips

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.