AutoComplete是属于比较常见的控件之一,在WEB开发中我们使用Ajax来实现自动完成。
在Android中,它自带了AutoCompleteTextView控件,通过它可以很容易的实现自动完成。
使用AutoCompleteTextView的步骤:
1.在布局文件中声明一个AutoCompleteTextView
<AutoCompleteTextView
android:id="@+id/autocompleteTextview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
2.定义提示条目的样式
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/autocompleteItem"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dip"
android:textColor="#0000FF"
/>
3.为AutoCompleteTextView提供一个ArrayAdapter
下面是完整的代码:
布局文件autocomplete.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择国家:"
/>
<AutoCompleteTextView
android:id="@+id/autocompleteTextview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
布局文件autocomplete_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/autocompleteItem"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dip"
android:textColor="#0000FF"
/>
Activity:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.and.test.R;
public class AutoCompleteActivity extends Activity {
private AutoCompleteTextView autoCompleteTextView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocompleteTextview);
List<String> countries = new ArrayList<String>();
countries.add("America");
countries.add("Ariabic");
countries.add("China");
countries.add("French");
countries.add("Finish");
countries.add("Finipino");
countries.add("中文测试1");
countries.add("中文测试2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.autocomplete_item,countries);
autoCompleteTextView.setAdapter(adapter);
}
}
显示的效果:
中文也是可以的:
至少要输入2个字符才会有提示。