android入门:自动完成字段

用到的关键控件:AutoCompleteTextView.

它的功能:用户已输入的文本作为前缀筛选条件与候选文本列表进行比较。匹配的结果将显示在一个选择列表中(实际上是Spinner)。

其中属性android:completionThreshold的值表示触发列表筛选功能之前,用户必须输入的最少字符数目。

下面的例子通过setAdapter()为AutoCompleteTextView提供一个适配器,适配器中包含候选值的列表。

新建一个android工程,需要改动的文件如下:

1.res/layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

    <TextView
        android:id="@+id/selection"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        />
    <AutoCompleteTextView
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="3"/>

</LinearLayout>

2.src/MainActivity.java

package com.example.autocomplete;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

public class MainActivity extends Activity implements TextWatcher{

	TextView selection;
	AutoCompleteTextView edit;
	String[] items={"lorem","ipsum","dolor","sit","amet","consectetuer","adipiscing",
			"elit","morbi","vel","ligula","vitae","arcu","aliquet","mollis",
			"etiam","vel","erat","plcacerat","ante","porttitor","sodales",
			"pellentesque","qugue","purus"};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		selection = (TextView)findViewById(R.id.selection);
		edit = (AutoCompleteTextView)findViewById(R.id.edit);
		edit.addTextChangedListener(this);
		edit.setAdapter(new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, items));
	}

	public void onTextChanged(CharSequence s, int start, int before, int count){
		selection.setText(edit.getText());
	}
	
	public void beforeTextChanged(CharSequence s, int start, int before, int count){
		//实现接口需要实现这个方法,但在这里用不到
	}
	
	public void afterTextChanged(Editable s){
		//实现接口需要实现这个方法,但在这里用不到
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

在模拟器上运行这个app,当用户输入比如lor,下拉列表自动出现lorem.

android入门:自动完成字段_第1张图片


你可能感兴趣的:(android入门:自动完成字段)