Android的AutoCompleteTextView与TextWatcher的结合

fmms 13年前

AutoCompleteTextView是实现动态匹配输入内容的一种输入框(EditText)

如输入“and”时,会提示“android”

package com.conowen.test;    import android.app.Activity;  import android.os.Bundle;  import android.text.Editable;  import android.text.TextWatcher;  import android.widget.AutoCompleteTextView;    public class DrComActivity extends Activity {     /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);          AutoCompleteTextView autoinput =(AutoCompleteTextView) findViewById(R.id.autoinput);         autoinput.setThreshold(1);// 输入一个字母就开始自动提示       autoinput.addTextChangedListener(new TextWatcher() {        @Override    public void onTextChanged(CharSequence s, int start, int before, int count) {     // TODO Auto-generated method stub     //s是输入框正在输的字符串,随着不断的输入,s的值也会不停地改变                                String str = s.toString();                             String[] temp = getInputAdapter(getInputWorldOrder(str));                 //此处代码省略,自己通过查询数据库或者其他方法,动态地获取相应的字符串数组                //如做一个字典时,不可能预先把所有单词做成一个adapter,应该根据输入的字符,               //动态地查询一定数量的相对应的单词,然后再构建adapter                ArrayAdapter<String> adapter = new ArrayAdapter<String>(ct,                android.R.layout.simple_dropdown_item_1line, temp);                      autoinput.setAdapter(adapter)                  //正在输入时,构建adapter,然后把adapter绑定在AutoCompleteTextView 上面      @Override    public void beforeTextChanged(CharSequence s, int start, int count,      int after) {     // TODO Auto-generated method stub      }      @Override    public void afterTextChanged(Editable s) {     // TODO Auto-generated method stub      }     }   }  }