软件编程
位置:首页>> 软件编程>> Android编程>> Android中AutoCompleteTextView与TextWatcher结合小实例

Android中AutoCompleteTextView与TextWatcher结合小实例

作者:conowen  发布时间:2023-11-07 06:27:22 

标签:Android,AutoCompleteTextView,TextWatcher

AutoCompleteTextView是实现动态匹配输入内容的一种输入框(EditText),如输入“and”时,会提示“Android”

效果图:

Android中AutoCompleteTextView与TextWatcher结合小实例

实现代码:


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

}

}
 }
}
0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com