Android动态自动匹配输入框
Posted yhw-miracle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android动态自动匹配输入框相关的知识,希望对你有一定的参考价值。
动态自动匹配输入框,可以分为单匹配和多匹配两种,如百度搜索框和邮箱发件人的输入框。
1.1 单匹配(AutoCompleteTextView)
- 初始化 AutoCompleteTextView 控件
- 需要一个适配器
- 初始化数据源
- 将 adapter 与 acTextView 绑定
1 AutoCompleteTextView acTextView = (AutoCompleteTextView)findViewById(R.id.AutoCompleteTextView1); 2 String[] data1 = {"android","Book","system","haha","hehe","shabi"}; 3 ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,data1); 4 acTextView.setAdapter(adapter1);
1.2 多匹配(MultiAutoCompleteTextView)
- 初始化 MultiAutoCompleteTextView 控件
- 需要一个适配器
- 初始化数据源
- 将 adapter 与 acTextView 绑定
- 设置分隔符
1 MultiAutoCompleteTextView macTextView = (MultiAutoCompleteTextView)findViewById(R.id.MultiAutoCompleteTextView1); 2 String[] data2 = {"123","12345","haharr","httt,"rr"}; 3 ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,data2); 4 macTextView.setAdapter(adapter2); 5 macTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
该方法只支持逗号连接,若需要自定义分隔符,需要自定义类,然后用语句
1 macTextView.setTokenizer(new SemicolonTokenizer(‘;‘));
执行。自定义分隔符类的代码如下。
1 import android.text.SpannableString; 2 import android.text.Spanned; 3 import android.text.TextUtils; 4 import android.widget.MultiAutoCompleteTextView; 5 6 /** 7 * Created by yhw-miracle on 2017/9/13. 8 * @effect 自定义 MultiAutoCompleteTextView 添加分隔符 9 */ 10 11 public class SemicolonTokenizer implements MultiAutoCompleteTextView.Tokenizer { 12 13 private char charS; 14 private String mSTring; 15 16 public SemicolonTokenizer(char charS) { 17 this.charS = charS; 18 mSTring = String.valueOf(charS); 19 } 20 21 @Override 22 public int findTokenStart(CharSequence text, int cursor) { 23 int i = cursor; 24 25 while (i > 0 && text.charAt(i - 1) != charS) { 26 i--; 27 } 28 while (i < cursor && text.charAt(i) == ‘ ‘) { 29 i++; 30 } 31 32 return i; 33 } 34 35 @Override 36 public int findTokenEnd(CharSequence text, int cursor) { 37 int i = cursor; 38 int len = text.length(); 39 40 while (i < len) { 41 if (text.charAt(i) == charS) { 42 return i; 43 } else { 44 i++; 45 } 46 } 47 48 return len; 49 } 50 51 @Override 52 public CharSequence terminateToken(CharSequence text) { 53 int i = text.length(); 54 55 while (i > 0 && text.charAt(i - 1) == ‘ ‘) { 56 i--; 57 } 58 59 if (i > 0 && text.charAt(i - 1) == charS) { 60 return text; 61 } else { 62 if (text instanceof Spanned) { 63 SpannableString sp = new SpannableString(text + mSTring); 64 TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0); 65 return sp; 66 } else { 67 return text + mSTring; 68 } 69 } 70 } 71 }