Simple usage of Autocompletetextview in Android (Implementing search History) _android

Source: Internet
Author: User

There are many tutorials on the web, the cue box character set is written in advance, for example, with a string[] array to contain the data, but we can also the user entered as a history record save

Here's the code I wrote first:

 Import android.app.Activity; 
Import android.content.SharedPreferences; 
Import Android.os.Bundle; 
Import Android.util.Log; 
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 Read_historyactivity extends activity implements Onclicklistener {private Autocompletetextview Autot 
 
  V /** called the activity is a. 
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    Autotv = (Autocompletetextview) Findviewbyid (R.ID.AUTOCOMPLETETEXTVIEW1); 
    Initautocomplete ("History", AUTOTV); 
    Button search = (button) Findviewbyid (R.id.button1); 
  Search.setonclicklistener (this); @Override public void OnClick (View v) {///Here you can set the save operation to execute when the search succeeds SaveHistory ("History ", AUTOTV); /** * Initializes the Autocompletetextview, displaying up to 5 prompts so that * Autocompletetextview automatically prompts * @param field to be saved at the beginning of the focus SHAREDPR Field name in Eference * @param auto to operate Autocompletetextview/private void Initautocomplete (String field,autocomplete 
    TextView Auto) {sharedpreferences sp = getsharedpreferences ("Network_url", 0); 
    String longhistory = sp.getstring ("History", "nothing"); 
    string[] Hisarrays = Longhistory.split (","); arrayadapter<string> adapter = new Arrayadapter<string> (this, Android. 
    R.layout.simple_dropdown_item_1line, hisarrays); 
      Keep only the most recent 50 records if (Hisarrays.length >) {string[] newarrays = new STRING[50]; 
      System.arraycopy (hisarrays, 0, newarrays, 0, 50); adapter = new Arrayadapter<string> (this, Android. 
    R.layout.simple_dropdown_item_1line, newarrays); 
    } auto.setadapter (adapter); 
    Auto.setdropdownheight (350); 
    Auto.setthreshold (1); Auto.setcomPletionhint ("recent 5 Records"); Auto.setonfocuschangelistener (New Onfocuschangelistener () {@Override public void Onfocuschange (View V, BOOL 
        Ean Hasfocus) {Autocompletetextview view = (Autocompletetextview) v; 
        if (hasfocus) {view.showdropdown (); 
  } 
      } 
    }); 
   /** * Saves the contents of the specified Autocompletetextview to the character segment specified in Sharedpreference * @param field name saved in Sharedpreference * @param auto to operate Autocompletetextview * * private void SaveHistory (String Field,autocompletetextview Auto) {S 
    Tring Text = Auto.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 (); } <span style= "Font-family:monospace; White-space:pre; BacKGROUND-COLOR:RGB (240, 240, 240); 
 ">}}</span>

The above code I implemented the Autocomplettextview from the sharepreference read history and display the function, when there is no input, prompted the latest 5 history (here can add a condition, when there is a history of the show)

Code that complements the layout

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Chemas.android.com/apk/res/android "android:orientation=" vertical "android:layout_width=" fill_parent "Android:lay"  
    out_height= "Fill_parent" > <textview android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:text= "@string/hello"/> <linearlayout android:layout_width= "0px" android:layout_height= "0px" a 
    Ndroid:focusable= "true" android:focusableintouchmode= "true" ></LinearLayout> <autocompletetextview android:hint= "Please enter text to search" android:layout_height= "wrap_content" android:layout_width= match_parent "android:id=" @ +id/autocompletetextview1 "> </AutoCompleteTextView> <button android:text=" search "android:id=" @+id/button1 "Android:layout_width=" wrap_content "android:layout_height=" wrap_content "></Button> </linearlayout > 

When there is a edittext or auto, when entering the screen is the default to get focus, to remove the focus, you can add an O-pixel before the layout, and set his first focus.

The effect chart is as follows

What appears below is the source content

It should be noted that some of the Autocompletetextview methods I used here

1. Setadapter () Method: The adapter parameters to be passed must be inherited from ListAdapter and Filterable, where both Arrayadapter and Simpleadapter can meet the requirements. We often use arrayadapter because he does not need to set his display position and TextView component like Simpleadapte.

To master it, you must check his source code, we can see how arrayadapter is implemented

Any adapter that inherits filterable must rewrite the GetFilter interface method.

Public Filter GetFilter () { 
  if (Mfilter = = null) { 
    mfilter = new Arrayfilter (); 
  } 
  return mfilter; 

This filter is the object that implements the filtering method, and again, we can see how his source code is implemented.

 /** * <p>an Array Filter constrains the content of the "array adapter with * a prefix. Each item this does not start with the supplied prefix * are removed from the list.</p> * * Private class ARR Ayfilter extends Filter {@Override protected filterresults performfiltering (charsequence prefix) {Filte 
 
      Rresults results = new filterresults (); if (moriginalvalues = = null) {synchronized (mlock) {moriginalvalues = new arraylist<t> (mobject 
        s); } if (prefix = null | | prefix.length () = = 0) {synchronized (mlock) {arraylist< 
          t> list = new arraylist<t> (moriginalvalues); 
          Results.values = list; 
        Results.count = List.size (); 
 
        } else {String prefixstring = prefix.tostring (). toLowerCase (); 
        Final arraylist<t> values = moriginalvalues; 
 
        Final int count = Values.size (); Final arraylist&Lt 
 
        t> newvalues = new arraylist<t> (count); 
          for (int i = 0; i < count; i++) {final T value = Values.get (i); 
 
          Final String ValueText = value.tostring (). toLowerCase (); The against the whole, non-splitted value if (Valuetext.startswith (prefixstring)) {New 
          Values.add (value); 
            else {final string[] words = Valuetext.split (""); 
 
            Final int wordCount = words.length; for (int k = 0; k < WordCount; k++) {if (Words[k].startswith (prefixstring)) {NewValue 
                S.add (value); 
              Break 
        }}} results.values = NewValues; 
      Results.count = Newvalues.size (); 
    return results; 
 }

This is a private inner class of arrayadapter custom, meaning that you can't modify this filtering method by inheriting, nor can you get the result set results after filtering. If you want to use the new filtering method, you must rewrite the GetFilter () method, and the filter object returned is the filter object you want to create (containing the performfiltering () method to reconstruct the filtering method you want)

2.setDropDownHeight method to set the height of the hint drop-down box, note that this only limits the height of the prompt drop-down box, suggesting that the number of datasets does not change

3.setThreshold method, setting prompts from the input of the first few characters

4.setCompletionHint method, set the text displayed at the bottom of the prompt box

5.setOnFocusChangeListener method, which contains Onfocuschangelistener listeners, setting focus to change events

6.showdropdown method, let the dropdown box bounce out

Some of the methods I didn't use enumerated

1.clearListSelection, remove the selector style, only temporarily remove, when the user again input and then appear again

2.dismissDropDown, close the Drop-down prompt box

3.enoughToFilter, this is a method to meet the filter conditions, the SDK recommended that we can rewrite this method

4. Getadapter, to get a filter list adapter

5.getDropDownAnchor, get the ID of the view of the anchor of the dropdown box

6.getDropDownBackground, get the background color of the dropdown box

7.setDropDownBackgroundDrawable, set the background color of the dropdown box

8.setDropDownBackgroundResource, setting the background resource for the dropdown box

9.setDropDownVerticalOffset, set the vertical offset of the Drop-down table, that is, the number of data items contained in the list

10.getDropDownVerticalOffset, get the vertical offset of the Drop-down table

11..setDropDownHorizontalOffset, set horizontal offset

12.setDropDownAnimationStyle, set the pop-up animation of the dropdown box

13.getThreshold, get the number of filtered characters

14.setOnItemClickListener, set dropdown box Click event

15.getListSelection, get the dropdown box selected as the location

16.getOnItemClickListener. Get a single click event

17.getOnItemSelectedListener Get Single selected event

18.getAdapter, get the adapter for that setting.
Some hidden methods and constructs I did not enumerate, can refer to the API document specifically

Custom:

Found on the internet are used together with arrayadapter, sometimes need a custom style, do? Follow me!
Look at the diagram, realize the empty input box content and delete item features.

Actually use Autocompletetextview to implement filter filterable, you have to tell it how to filter. Since Arrayadapter has helped us implement the Filterable interface, we can easily ignore this, thinking that Autocompletetextview is easy to use. What if you're using a baseadapter? Of course, in fact it is not difficult, as long as it also implements the Filterable interface can be.

The following is the source code:

Implementing a Custom Adapter

Import java.util.ArrayList; 
 
Import java.util.List; 
 
Import QIANLONG.QLMOBILE.TABLET.CSCO.R; 
Import Android.content.Context; 
Import Android.util.Log; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
Import Android.view.ViewGroup; 
Import Android.view.View.OnClickListener; 
Import Android.widget.BaseAdapter; 
Import Android.widget.Filter; 
Import android.widget.Filterable; 
Import Android.widget.ImageView; 
 
Import Android.widget.TextView; 
  public class Autocompleteadapter extends Baseadapter implements filterable{private context; 
  Private Arrayfilter Mfilter; Private arraylist<string> moriginalvalues;//All item private list<string> mobjects;//filtered item Private fin 
  Al Object Mlock = new Object (); The private int maxmatch=10;//displays up to a maximum number of options, with negative numbers representing all public autocompleteadapter (context context,arraylist<string> 
    Moriginalvalues,int maxmatch) {this.context=context; 
    This.moriginalvalues=moriginalvalues; This.maxmatch=maxMatch;  
      @Override public Filter GetFilter () {//TODO auto-generated Method Stub if (Mfilter = null) {  
    Mfilter = new Arrayfilter (); 
  return mfilter; Private class Arrayfilter extends Filter {@Override protected filterresults performfiltering (charseq  
        
Uence prefix) {//TODO auto-generated method stub filterresults results = new filterresults (); if (moriginalvalues = = null) {//synchronized (Mlock) {//moriginalvalues = new arraylist< String> (mobjects)////////////} if (prefix = null | | prefix.length () = 0) {s 
          Ynchronized (Mlock) {log.i ("tag", "Moriginalvalues.size=" +moriginalvalues.size ());  
          arraylist<string> list = new arraylist<string> (moriginalvalues);  
          Results.values = list;  
          Results.count = List.size (); 
        return results; }} else {
        String prefixstring = prefix.tostring (). toLowerCase ();  
  
        Final int count = Moriginalvalues.size ();  
  
        Final arraylist<string> newvalues = new arraylist<string> (count);  
          for (int i = 0; i < count; i++) {final String value = Moriginalvalues.get (i);  
  
Final String ValueText = Value.tolowercase (); if (Valuetext.contains (prefixstring)) {//Match all///////I match against th e whole, non-splitted value if (Valuetext.startswith (prefixstring)) {//source code, matching the opening newvalues.add (VA  
          Lue); }/else {//final string[] words = Valuetext.split ("");//delimiter matching, inefficient/final int wo  
Rdcount = Words.length; for (int k = 0; k < WordCount; k++) {//if (Words[k].startswith (prefixstring)) {/  
/Newvalues.add (value);  
Break //              }  
////} if (maxmatch>0) {//There is a quantity limit if (Newvalues.size () >maxmatch-1) {//Not too  
            multiple break;  
        }} results.values = NewValues;  
      Results.count = Newvalues.size (); 
    return results;  } @Override protected void Publishresults (charsequence constraint, filterresults results) {//  
      TODO auto-generated Method Stub mobjects = (list<string>) results.values;  
      if (Results.count > 0) {notifydatasetchanged ();  
      else {notifydatasetinvalidated (); @Override public int GetCount () {//TODO auto-generated a stub return mobjects 
  . Size (); 
    @Override public Object getitem (int position) {//TODO auto-generated stub//This method is incorrect, try not to use 
  return Mobjects.get (position); @Override public long getitemid (int position) {//TODO auto-generated method stub return position; @Override Public View getview (final int position, View Convertview, ViewGroup parent) {//TODO Auto-genera 
    Ted Method stub Viewholder holder = null; 
      if (convertview==null) {holder=new viewholder (); 
      Layoutinflater Inflater = (layoutinflater) context.getsystemservice (Context.layout_inflater_service); 
      Convertview=inflater.inflate (r.layout.simple_list_item_for_autocomplete, NULL);  
      holder.tv= (TextView) Convertview.findviewbyid (R.ID.SIMPLE_ITEM_0); 
      holder.iv= (ImageView) Convertview.findviewbyid (r.id.simple_item_1); 
    Convertview.settag (holder); 
    }else{holder = (viewholder) convertview.gettag (); 
    } holder.tv.setText (Mobjects.get (position)); 
        Holder.iv.setOnClickListener (New Onclicklistener () {@Override public void OnClick (View v) { TODO auto-generated Method Stub String Obj=mobjects.remOve (position); 
        Moriginalvalues.remove (obj); 
      Notifydatasetchanged (); 
    } 
    }); 
  return convertview; 
    Class Viewholder {TextView TV; 
  ImageView IV; 
  Public arraylist<string> Getallitems () {return moriginalvalues; 
 } 
}
Import Android.content.Context; 
Import Android.util.AttributeSet; 
Import Android.view.View; 
Import Android.widget.AutoCompleteTextView; 
Import Android.widget.ImageView; 
Import Android.widget.RelativeLayout; 
 
Import Android.widget.ImageView.ScaleType; 
  public class Advancedautocompletetextview extends relativelayout{the private context; 
  Private Autocompletetextview TV; 
    Public Advancedautocompletetextview {Super (context); 
  TODO auto-generated constructor stub this.context=context; 
    Public Advancedautocompletetextview (context, AttributeSet attrs) {Super (context, attrs); 
  TODO auto-generated constructor stub this.context=context; 
    } @Override protected void Onfinishinflate () {super.onfinishinflate (); 
  Initviews (); private void Initviews () {relativelayout.layoutparams params=new relativelayout.layoutparams (relativelayout.l Ayoutparams.fill_parent,relativelayout.layoUtparams.wrap_content); 
    Tv=new Autocompletetextview (context); 
    Tv.setlayoutparams (params); 
Tv.setpadding (10, 0, 40, 0); 
     
    Tv.setsingleline (TRUE); Relativelayout.layoutparams p=new relativelayout.layoutparams (RelativeLayout.LayoutParams.WRAP_CONTENT, 
    RelativeLayout.LayoutParams.WRAP_CONTENT); 
    P.addrule (Relativelayout.align_parent_right); 
    P.addrule (relativelayout.center_vertical); 
    p.rightmargin=10; 
    ImageView iv=new ImageView (context); 
    Iv.setlayoutparams (P); 
    Iv.setscaletype (Scaletype.fit_center); 
    Iv.setimageresource (R.drawable.delete); 
    Iv.setclickable (TRUE); 
        Iv.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) { 
      TODO auto-generated Method Stub Tv.settext (""); 
       
    } 
    }); 
    This.addview (TV); 
     
     
  This.addview (iv); 
  public void Setadapter (Autocompleteadapter adapter) {Tv.setadapter (adapter); }
   
  public void Setthreshold (int threshold) {tv.setthreshold (threshold); 
  Public Autocompletetextview Getautocompletetextview () {return TV; 
 } 
}

Simple_list_item_for_autocomplete.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:layout_width=" fill_parent " 
  android:layout_height=" wrap_content " 
  android:o" rientation= "Horizontal" 
  android:paddingtop= "5dip" 
  android:paddingbottom= "5dip" 
  > 
  < TextView android:id= "@+id/simple_item_0" 
    android:layout_width= "Fill_parent" 
    Wrap_content " 
    android:layout_weight=" 1 " 
    android:paddingleft=" 5dip " 
    android:textcolor=" @android: Color/black " 
    /> 
  <imageview android:id=" @+id/simple_item_1 "android:layout_width=" Wrap_ 
    Content " 
    android:layout_height=" wrap_content " 
    android:scaletype=" Fitcenter " 
    android:src=" @ Drawable/delete " 
    android:layout_centervertical=" true " 
    android:layout_marginright=" 5dip " 
    /> 

Used, as is often the case:  

 private Advancedautocompletetextview TV; 
  Private Autocompleteadapter adapter; 
  Private arraylist<string> moriginalvalues=new arraylist<string> (); 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.main); 
    Moriginalvalues.add ("1234561"); 
    Moriginalvalues.add ("1234562"); 
    Moriginalvalues.add ("2234563"); 
    Moriginalvalues.add ("2234564"); 
    Moriginalvalues.add ("3234561111"); 
    Moriginalvalues.add ("32345622222"); 
    Moriginalvalues.add ("323456333333"); 
    Moriginalvalues.add ("3234564444"); 
    Moriginalvalues.add ("3234565555"); 
    Moriginalvalues.add ("32345666666"); 
     
    Moriginalvalues.add ("32345777777"); 
    TV = (Advancedautocompletetextview) Findviewbyid (r.id.tv); 
    Tv.setthreshold (0); 
    adapter = new Autocompleteadapter (this, moriginalvalues, 10); 
  Tv.setadapter (adapter); } 

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.