android中AutoCompleteTextView的简单用法(实现搜索历史)

android中AutoCompleteTextView的简单用法(实现搜索历史),第1张

概述网上有不少教程,那个提示框字符集都是事先写好的,例如用一个String[]数组去包含了这些数据,但是,我们也可以吧用户输入的作为历史记录保存

网上有不少教程,那个提示框字符集都是事先写好的,例如用一个String[] 数组去包含了这些数据,但是,我们也可以吧用户输入的作为历史记录保存

下面先上我写的代码:

 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 autoTv;    /** Called when the activity is first created. */   @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) {     // 这里可以设定:当搜索成功时,才执行保存 *** 作     saveHistory("history",autoTv);   }    /**    * 初始化autoCompleteTextVIEw,最多显示5项提示,使    * autoCompleteTextVIEw在一开始获得焦点时自动提示    * @param fIEld 保存在sharedPreference中的字段名    * @param auto 要 *** 作的autoCompleteTextVIEw    */   private voID initautoComplete(String fIEld,autoCompleteTextVIEw 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);     //只保留最近的50条的记录     if(hisArrays.length > 50){       String[] newArrays = new String[50];       System.arraycopy(hisArrays,newArrays,50);       adapter = new ArrayAdapter<String>(this,newArrays);     }     auto.setAdapter(adapter);     auto.setDropDownHeight(350);     auto.setThreshold(1);     auto.setCompletionHint("最近的5条记录");     auto.setonFocuschangelistener(new OnFocuschangelistener() {       @OverrIDe       public voID onFocusChange(VIEw v,boolean hasFocus) {         autoCompleteTextVIEw vIEw = (autoCompleteTextVIEw) v;         if (hasFocus) {             vIEw.showDropDown();         }       }     });   }      /**    * 把指定autoCompleteTextVIEw中内容保存到sharedPreference中指定的字符段    * @param fIEld 保存在sharedPreference中的字段名    * @param auto 要 *** 作的autoCompleteTextVIEw    */   private voID saveHistory(String fIEld,autoCompleteTextVIEw auto) {     String 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 > } }</span> 

上面的代码我实现了autocomplettextvIEw的从sharepreference中读取历史记录并显示的功能,当没有任何输入时,提示最新的5项历史记录(这里可以加个条件,当有历史记录时才显示)

补上布局的代码

<?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">   <TextVIEw androID:layout_wIDth="fill_parent"     androID:layout_height="wrap_content"     androID:text="@string/hello" />   <linearLayout androID:layout_wIDth="0px"     androID:layout_height="0px" androID:focusable="true"     androID:focusableIntouchMode="true"></linearLayout>   <autoCompleteTextVIEw     androID:hint="请输入文字进行搜索" androID:layout_height="wrap_content"     androID:layout_wIDth="match_parent"     androID:ID="@+ID/autoCompleteTextVIEw1">   </autoCompleteTextVIEw>   <button androID:text="搜索" androID:ID="@+ID/button1"     androID:layout_wIDth="wrap_content"     androID:layout_height="wrap_content"></button> </linearLayout> 

当之有一个edittext或者auto的时候,进入画面时是默认得到焦点的,要想去除焦点,可以在auto之前加一个o像素的layout,并设置他先得到焦点。

效果图如下


下面出现的是源码内容 

需要注意的是,我这里用到的autoCompleteTextVIEw的几个方法

1. setAdapter()方法:这里要传递的adapter参数必须是继承listadapter和Filterable的,其中arrayAdapter和simpleAdapter都能满足要求,我们常用arrayAdapter,因为他不需要像simpleAdapte那样设置他的显示位置和textvIEw组件。

要想掌握它,就必须查看他的源码,我们可以看看arrayadapter是如何实现

凡是继承了Filterable的adapter都必须重写getFilter接口方法

public Filter getFilter() {   if (mFilter == null) {     mFilter = new ArrayFilter();   }   return mFilter; } 

这个filter 就是实现过滤方法的对象,同样,我们可以查看他的源码是如何实现的
 

 /**   * <p>An array filter constrains the content of the array adapter with   * a prefix. Each item that does not start with the supplIEd prefix   * is removed from the List.</p>   */   private class ArrayFilter extends Filter {     @OverrIDe     protected FilterResults performFiltering(CharSequence prefix) {       FilterResults results = new FilterResults();        if (mOriginalValues == null) {         synchronized (mlock) {           mOriginalValues = new ArrayList<T>(mObjects);         }       }        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<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();            // First match against the whole,non-splitted value           if (valueText.startsWith(prefixString)) {             newValues.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)) {                 newValues.add(value);                 break;               }             }           }         }          results.values = newValues;         results.count = newValues.size();       }        return results;     } 

这是arrayAdapter自定义的一个私有内部类,所谓私有,就意味着你不能通过继承去修改这种过滤方法,同样你也不能直接得到他过滤后结果集results。假如你想使用新的过滤方法,你必须重写getfilter()方法,返回的filter对象是你要新建的filter对象(在里面包含performFiltering()方法重新构造你要的过滤方法)

2.setDropDownHeight方法 ,用来设置提示下拉框的高度,注意,这只是限制了提示下拉框的高度,提示数据集的个数并没有变化

3.setThreshold方法,设置从输入第几个字符起出现提示

4.setCompletionHint方法,设置提示框最下面显示的文字

 5.setonFocuschangelistener方法,里面包含OnFocuschangelistener监听器,设置焦点改变事件

 6.showdropdown方法,让下拉框d出来       

我没有用到的一些方法列举

1.clearListSelection,去除selector样式,只是暂时的去除,当用户再输入时又重新出现

2.dismissDropDown,关闭下拉提示框

3.enoughToFilter,这是一个是否满足过滤条件的方法,sdk建议我们可以重写这个方法

4. getAdapter,得到一个可过滤的列表适配器

5.getDropDownAnchor,得到下拉框的锚计的vIEw的ID

6.getDropDownBackground,得到下拉框的背景色

7.setDropDownBackgroundDrawable,设置下拉框的背景色

8.setDropDownBackgroundResource,设置下拉框的背景资源

9.setDropDownVerticalOffset,设置下拉表垂直偏移量,即是List里包含的数据项数目

10.getDropDownVerticalOffset ,得到下拉表垂直偏移量

11..setDropDownHorizontalOffset,设置水平偏移量

12.setDropDownAnimationStyle,设置下拉框的d出动画

13.getThreshold,得到过滤字符个数

14.setonItemClickListener,设置下拉框点击事件

15.getListSelection,得到下拉框选中为位置

16.getonItemClickListener。得到单项点击事件

17.getonItemSelectedListener得到单项选中事件

18.getAdapter,得到那个设置的适配器
一些隐藏方法和构造我没有列举了,具体可以参考api文档

自定义:

网上找到的都是同ArrayAdapter一起使用的,有时候需要自定义风格,咋办?follow me!


看上图,实现了清空输入框内容和删除Item功能。

其实使用autoCompleteTextVIEw就得实现过滤器Filterable,你得告诉它怎么过滤。由于ArrayAdapter已经帮我们实现了Filterable接口,所以我们很容易忽略这个,以为autoCompleteTextVIEw用起来很简单。如果你使用的是BaseAdapter呢?当然,事实上也不难,只要让它也实现Filterable接口就可以了。

下面是源码:

实现自定义的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 context;   private ArrayFilter mFilter;   private ArrayList<String> mOriginalValues;//所有的Item   private List<String> mObjects;//过滤后的item   private final Object mlock = new Object();   private int maxMatch=10;//最多显示多少个选项,负数表示全部   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(CharSequence 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) {          synchronized (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)){//匹配所有 //            //          }           // First match against the whole,non-splitted value            if (valueText.startsWith(prefixString)) { //源码,匹配开头             newValues.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)) {  //                newValues.add(value);  //                break;  //              }  //            }  //          }           if(maxMatch>0){//有数量限制              if(newValues.size()>maxMatch-1){//不要太多                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 method stub     return mObjects.size();   }    @OverrIDe   public Object getItem(int position) {     // Todo auto-generated method stub     //此方法有误,尽量不要使用     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-generated 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{    private Context context;   private autoCompleteTextVIEw tv;   public AdvancedautoCompleteTextVIEw(Context context) {     super(context);     // Todo auto-generated constructor stub     this.context=context;   }   public AdvancedautoCompleteTextVIEw(Context 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.LayoutParams.FILL_PARENT,relativeLayout.LayoutParams.WRAP_CONTENT);     tv=new autoCompleteTextVIEw(context);     tv.setLayoutParams(params);     tv.setpadding(10,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:orIEntation="horizontal"   androID:paddingtop="5dip"   androID:paddingBottom="5dip"   >   <TextVIEw androID:ID="@+ID/simple_item_0"     androID:layout_wIDth="fill_parent"     androID:layout_height="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"     /> </linearLayout> 

使用,通常情况下都这样: 

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);   } 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的android中AutoCompleteTextView的简单用法(实现搜索历史)全部内容,希望文章能够帮你解决android中AutoCompleteTextView的简单用法(实现搜索历史)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1147774.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存