1. 程式人生 > >AutoCompleteTextView輸入兩個字元後才給提示列表

AutoCompleteTextView輸入兩個字元後才給提示列表

        在Android中使用自動提示輸入,控制元件為AutoCompleteTextView型別物件autoText,當給autoText設定介面卡時,繼承自ListAdapter或者BaseAdapter,需要實現介面Filter,並且自定義實現Filter子類。

public class AutoCompleteAdapter extends BaseAdapter implements Filterable{

    private Context context;
    private ArrayFilter mFilter;
    private List<String> mObjects;//過濾後的item
    private final Object mLock = new Object();
    private int maxMatch = 100;//最多顯示多少個選項,負數表示全部

    public AutoCompleteAdapter(Context context) {
        this.context = context;
    }

    @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 (prefix == null || prefix.length() == 0) {
                synchronized (mLock) {
                    ArrayList<String> list = new ArrayList<String>();
                    results.values = list;
                    results.count = list.size();
                    return results;
                }
            } else {
                String prefixString = prefix.toString();
                
                final ArrayList<String> newValues = new ArrayList<String>();
                ...
                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.list_item_login_users, null);
            holder.tv = (TextView) convertView.findViewById(android.R.id.text1);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tv.setText(mObjects.get(position));
        return convertView;
    }

    class ViewHolder {
        TextView tv;
    }
        給autoText設定介面卡

autoText.setAdapter(new AutoCompleteAdapter(getApplicationContext()));
        這時,發現只有在輸入字元超過兩個字元時才會給出下拉提示列表。在AutoCompleteTextView原始碼中找到處理文字變更的方法:

void doAfterTextChanged() {
        if (mBlockCompletion) return;

        // if the list was open before the keystroke, but closed afterwards,
        // then something in the keystroke processing (an input filter perhaps)
        // called performCompletion() and we shouldn't do any more processing.
        if (DEBUG) Log.v(TAG, "after text changed: openBefore=" + mOpenBefore
                + " open=" + isPopupShowing());
        if (mOpenBefore && !isPopupShowing()) {
            return;
        }

        // the drop down is shown only when a minimum number of characters
        // was typed in the text view
        if (enoughToFilter()) {
            if (mFilter != null) {
                mPopupCanBeUpdated = true;
                performFiltering(getText(), mLastKeyCode);
            }
        } else {
            // drop down is automatically dismissed when enough characters
            // are deleted from the text view
            if (!mPopup.isDropDownAlwaysVisible()) {
                dismissDropDown();
            }
            if (mFilter != null) {
                mFilter.filter(null);
            }
        }
    }
        這個方法裡有一個if(enoughFilter())的判斷,為true時才對字元進行判斷,為false直接傳null給filter()方法;那個這個enoughFilter()是什麼呢?看下面程式碼:
    /**
     * Returns <code>true</code> if the amount of text in the field meets
     * or exceeds the {@link #getThreshold} requirement.  You can override
     * this to impose a different standard for when filtering will be
     * triggered.
     */
    public boolean enoughToFilter() {
        if (DEBUG) Log.v(TAG, "Enough to filter: len=" + getText().length()
                + " threshold=" + mThreshold);
        return getText().length() >= mThreshold;
    }
        這個方法,判斷的是變更後文字的長度跟mThreshold這個值的大小比較,mThreshold是一個private的整型變數;這個變數有個預設的初始值為2:
public AutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        ...

        TypedArray a =
            context.obtainStyledAttributes(
                attrs, com.android.internal.R.styleable.AutoCompleteTextView, defStyle, 0);

        mThreshold = a.getInt(
                R.styleable.AutoCompleteTextView_completionThreshold, 2);

        ...

        a.recycle();

        ...
    }
        看到這裡,就明白了,需要設定Threshold的初始值,這個初始可以在XML中設定,也可以在Java程式碼中設定。
android:completionThreshold="1"
autoText.setThreshold(1);

相關推薦

AutoCompleteTextView輸入字元提示列表

        在Android中使用自動提示輸入,控制元件為AutoCompleteTextView型別物件autoText,當給autoText設定介面卡時,繼承自ListAdapter或者BaseAdapter,需要實現介面Filter,並且自定義實現Filter子類

java中輸入字元,按各字元的ASCII碼從小到大的順序輸出這三字元

import java.util.Scanner; public class Main {     public static void main(String[] args) {         Scanne

編寫一個Java應用程式,當用戶在輸入對話方塊中輸入日期(日期格式為YYYYMMDD,如1999年1月12日應輸入為19990112),程式將判斷日期的先後順序,以及日期之間的間隔天數(例

編寫一個Java應用程式,當用戶在輸入對話方塊中輸入兩個日期後(日期格式為YYYYMMDD, 如1999年1月12日應輸入為19990112), 程式將判斷兩個日期的先後順序, 以及兩個日期之間的間隔天數(例如1999年1月1日和1999年1月2日之間的間隔是1天。  

關於輸入字元知識點

比如7-6 計算火車執行時間 要用到輸入輸出中的一個知識點。 通過在格式符d之前加上列數,表明輸入整數資料的列數。 如兩列就寫成%2d 對於scanf("%2d%2d%2d%2d",&h1,&

C語言中用scanf連續輸入字元型別的問題

   今天上網查了下才知道,原來scanf是從標準輸入緩衝區中讀取輸入的資料,而%c的字元輸入格式會接收回車字元,在輸入第一個scanf時輸入字元後按 回車結束,輸入緩衝中儲存了這個回車符,遇到第二個scanf時,它自動把這個回車符賦給了ch2。而如果第二個scanf的輸入格式不是%c時,由於格 式不匹配,

27、輸入單調遞增的鏈表,輸出鏈表合成的鏈表,當然我們需要合成的鏈表滿足單調不減規則。

-s st2 image code solution 兩個 cnblogs 思路 div 輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。 思路:同歸並算法 本題: 1 public class Solution {

c語言 用getchar函式讀入字元c1 c2 用putchar和printf輸出 思考問題

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

輸入長度相同的字串,比較個數在相同位置的字元是否相同

#include<iostream> #include<string.h>//因為要測字串長度,所以要加標頭檔案; using namespace std; int main() { char a[10],b[10];//根據題意而設定字串大小; int i,j=0,

輸入字串,建立一個單鏈表,操作單鏈表使每相鄰的字元交換位置

  題目如上圖所示 ,程式碼如下: #include <iostream> #include <string> using namespace std; stru

用Python寫一段程式碼,實現接收使用者輸入的數字並輸出數字相加的結果,要求使用者輸入任何內容程式不會報錯

分別採用基礎方法和異常處理方法實現。 基礎方法程式碼如下: num1 = input('請輸入數字1:') if num1.strip() == '': print('輸入錯誤。') exit() elif num1[0] != '.': for

輸入整數m和n,及另一個整數k,計算m/n,結果精確到小數點k位。

#include<stdio.h> int main() { int m,n,k,i; printf("Please input integer m , n and k\n"); scanf("%d%d%d",&m,&n,&k); pri

輸入字元(可以重複),按各字元的ASCII碼從小到大的順序輸出這三字元

import java.util.Scanner; public class Main {public static void main(String[] args) {// TODO Auto-generated method stub Scanner input =ne

劍指offer-輸入單調遞增的連結串列,輸出連結串列合成的連結串列,當然我們需要合成的連結串列滿足單調不減規則。

既然是有序連結串列,可以考慮使用分治思想,實現程式碼如下:/* public class ListNode { int val; ListNode next = null; L

劍指offer--輸入單調遞增的連結串列,輸出連結串列合成的連結串列,當然我們需要合成的連結串列滿足單調不減規則。

合併兩個有序連結串列是一道很常見的提醒,可以利用分治思想用遞迴實現,或者是不用遞迴,遞迴比較難理解。下面給出非遞迴的方法。 /* public class ListNode { int val

Python練習題8(替換相同的字符串並輸出):輸入字母串,將字母串都包含的字母用'_'替換,輸出字母串的剩余部分 (不能為空串,區別大小寫,只能包含字母)

format pre 兩個 div form tput nco encode col 方法一:檢查輸入是否為空串,循環字母串,相同的則替換,然後再用replace()方法去除,輸出想要的結果 1 def str_replace(messages1,messages2):

Python練習題8(替換相同的字串並輸出):輸入字母串,將字母串都包含的字母用'_'替換,輸出字母串的剩餘部分 (不能為空串,區別大小寫,只能包含字母)

方法一:檢查輸入是否為空串,迴圈字母串,相同的則替換,然後再用replace()方法去除,輸出想要的結果 1 def str_replace(messages1,messages2): 2 if messages1.strip() == '' or messages2.strip() ==

strcat拼接字元指標,釋放記憶體崩潰問題

在實際開放中,我們可能會用到strcat拼接兩個字串,例如 char a[6] = "hello"; char b[6] = "world"; strcat(a,b); free(a); free(b); 此時會出現越界情況,由於a只有6個字元的空間,拼接後超出了本身空

JS判斷輸入字串長度(漢字算字元,字母數字算一個)

<html> <head> <title>js判斷輸入字串長度(漢字算兩個字元,字母數字算一個)</title> <style type="text/css"> .pbt { margin-b

筆試題:輸入正整數a和b,然後分別將他們的數字按照高位在右邊的 方式反轉求和!

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String

c語言:用getchar函式讀入字元c1,c2,用putchar和printf輸出。思考問題

用getchar函式讀入兩個字元給c1,c2,分別用putchar和printf輸出這兩個字元。思考以下問題:(1)變數c1和c2定義為字元型還是整型?或二者皆可?(2)要求輸出c1和c2的ASCII碼,應如何處理?(3)整形變數和字元變數是否在任何情況下都可以互相代替?ch