Android自動提示文字框改為其他分隔——(多次提示)
阿新 • • 發佈:2018-11-28
要想改為其他的分隔符需再寫個類
SemicolonTokenizer類
package com.example.android_06; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.widget.MultiAutoCompleteTextView; public class SemicolonTokenizer implements MultiAutoCompleteTextView.Tokenizer { private char charS; private String mSTring; //構造方法 public SemicolonTokenizer(char charS) { this.charS = charS; mSTring = String.valueOf(charS); } public int findTokenStart(CharSequence text, int cursor) { int i = cursor; while (i > 0 && text.charAt(i - 1) != charS) { i--; } while (i < cursor && text.charAt(i) == ' ') { i++; } return i; } public int findTokenEnd(CharSequence text, int cursor) { int i = cursor; int len = text.length(); while (i < len) { if (text.charAt(i) == charS) { 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) == charS) { return text; } else { if (text instanceof Spanned) { SpannableString sp = new SpannableString(text + mSTring); TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0); return sp; } else { return text + mSTring; } } } }
MainActivity類
package com.example.android_06; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.MultiAutoCompleteTextView; import android.widget.SimpleAdapter; import android.widget.Spinner; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity { // 高階控制元件搜尋提示框(多次提示) private String[] data4; private ArrayAdapter adapter4; private MultiAutoCompleteTextView mactv_main_context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * 高階控制元件搜尋提示框(多次提示)(作業) */ data4 = new String[]{ "憤怒的小鳥", "湯姆貓", "落湯雞", "牛牛", "哈巴狗", "神龍", "烤鴨", "小象", "美人魚", "九尾狐" }; adapter4 = new ArrayAdapter(this,R.layout.actv_main_item1,data4); MultiAutoCompleteTextView.Tokenizer t = new MultiAutoCompleteTextView.CommaTokenizer(); mactv_main_context.setTokenizer(t); //設定你想要的分隔符 mactv_main_context.setTokenizer(new SemicolonTokenizer(';')); mactv_main_context.setAdapter(adapter4); } /** * 初始化 */ public void initView(){ actv_main_context = findViewById(R.id.actv_main_context); spinner_main_img = findViewById(R.id.spinner_main_img); mactv_main_context = findViewById(R.id.mactv_main_context); } }