AutoCompleteTextView
AutoCompleteTextView是EditText的subclass,可以使用EditText所有的属性,例如字体,颜色等。此外,提供android:completionThreshold,用于表明最小要敲入多少字符才开始显示list filter。我们可以通过setAdapter设置一个adapter来给出list的内容,但是由于用户可以自行填入内容,因此不支持selected listener,我们可以注册一个TextWatcher,就如同其他EditText widget一样,来检测特系统的变化,它在用户从list中选择或者人工填入都可以监测到。
public class MainActivity extends Activity implements TextWatcher { private AutoCompleteTextView atv; private TextView tv; private ArrayAdapter<CharSequence> adapter; @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub tv.setText(atv.getText()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); atv = (AutoCompleteTextView) findViewById(R.id.atv); tv = (TextView) findViewById(R.id.textView1); adapter = ArrayAdapter.createFromResource(this, R.array.test, android.R.layout.simple_dropdown_item_1line); atv.setAdapter(adapter); atv.addTextChangedListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }