Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android中AutoCompleteTextView的簡單用法(實現搜索歷史)

android中AutoCompleteTextView的簡單用法(實現搜索歷史)

編輯:關於Android編程

網上有不少教程,那個提示框字符集都是事先寫好的,例如用一個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, 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("最近的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方法,讓下拉框彈出來       

我沒有用到的一些方法列舉

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,設置下拉框的彈出動畫

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved