临文乍了了,彻卷兀若无。这篇文章主要讲述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 13private char charS; 14private String mSTring; 15 16public SemicolonTokenizer(char charS) { 17this.charS = charS; 18mSTring = String.valueOf(charS); 19} 20 21@Override 22public int findTokenStart(CharSequence text, int cursor) { 23int i = cursor; 24 25while (i > 0 & & text.charAt(i - 1) != charS) { 26i--; 27} 28while (i < cursor & & text.charAt(i) == ‘ ‘) { 29i++; 30} 31 32return i; 33} 34 35@Override 36public int findTokenEnd(CharSequence text, int cursor) { 37int i = cursor; 38int len = text.length(); 39 40while (i < len) { 41if (text.charAt(i) == charS) { 42return i; 43} else { 44i++; 45} 46} 47 48return len; 49} 50 51@Override 52public CharSequence terminateToken(CharSequence text) { 53int i = text.length(); 54 55while (i > 0 & & text.charAt(i - 1) == ‘ ‘) { 56i--; 57} 58 59if (i > 0 & & text.charAt(i - 1) == charS) { 60return text; 61} else { 62if (text instanceof Spanned) { 63SpannableString sp = new SpannableString(text + mSTring); 64TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0); 65return sp; 66} else { 67return text + mSTring; 68} 69} 70} 71 }
【Android动态自动匹配输入框】
推荐阅读
- Android8.0通知
- 安卓手机传递文件到Windows系统电脑
- Cordova????????????App?????? - ??????
- Twitter数据挖掘(使用Python进行大数据分析的指南)
- 迁移旧数据而不用担心
- HDFS教程,适用于陷入关系数据库的数据分析师
- 一致哈希指南
- 权威的NoSQL数据库指南
- 非传统数据存储的数据工程师指南