android how an EditText work as AutoComplete

前端 未结 5 1607
孤独总比滥情好
孤独总比滥情好 2020-12-03 02:38

I want my EditText should work as AutoComplete, for that I write in XML file

android:inputType=\"textAutoComplete|textAutoCorrect\"         


        
5条回答
  •  旧时难觅i
    2020-12-03 03:21

    This code for change settings of MultiAutoCompleteTextView

    ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,codeKeyWords);
    MultiAutoCompleteTextView autoCompleteTextView1 = (MultiAutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
    autoCompleteTextView1.setAdapter(adapter);
    autoCompleteTextView1.setThreshold(1);
    autoCompleteTextView1.setTokenizer(new this.CommaTokenizer());
    

    And below that code for make spliting words by space char and \n charactes.. (Why we need this code? Because Normal multiAutoComplete.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); like that and it make spliting the words by ',' character, But our code help you to make that spliting by these characters ' ' and '\n' )

    /**
             * This simple Tokenizer can be used for lists where the items are
             * separated by a comma and one or more spaces.
             */
        public static class CommaTokenizer implements Tokenizer {
            public int findTokenStart(CharSequence text, int cursor) {
                int i = cursor;
    
                while (i > 0 && text.charAt(i - 1) != ' ') {
                    i--;
                }
                while (i < cursor && text.charAt(i) == '\n') {
                    i++;
                }
    
                return i;
            }
    
            public int findTokenEnd(CharSequence text, int cursor) {
                int i = cursor;
                int len = text.length();
    
                while (i < len) {
                    if (text.charAt(i) == '\n') {
                        return i;
                    } else {
                        i++;
                    }
                }
    
                return len;
            }
    
            public CharSequence terminateToken(CharSequence text) {
                int i = text.length();
    
                while (i > 0 && text.charAt(i - 1) == ' ') {
                    i--;
                }
    
                if (i > 0 && text.charAt(i - 1) == ' ') {
                    return text;
                } else {
                    if (text instanceof Spanned) {
                        SpannableString sp = new SpannableString(text + "\n");
                        TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
                                                Object.class, sp, 0);
                        return sp;
                    } else {
                        return text + " ";
                    }
                }
            }
    

提交回复
热议问题