1.实现AutoCompleteTextView的基本显示效果
效果:
list_items.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/list_items_textViewId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="15sp"
android:lines="1"/>
</LinearLayout>
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="单词:" />
<AutoCompleteTextView
android:id="@+id/autoCompleteTextViewId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入……"
android:layout_toRightOf="@id/textViewId"
/>
</RelativeLayout>
MainActivity.java:
package com.haut.a11_autocompletetextview;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends Activity {
private AutoCompleteTextView autoComplete;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextViewId);
// 创建一个容器存储数据
List<String> list = new ArrayList<String>();
list.add("above");
list.add("add");
list.add("allow");
list.add("aptment");
list.add("alone");
// 也可以用一个数组为适配器提供数据
String[] data = new String[] { "张一一", "张一二", "张一三", "张一思", "张一武", "张一六" };
// 创建ArrayAdapter,这里的data可以换成list,都是存放数据的容器
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.list_items, R.id.list_items_textViewId, data);
autoComplete.setAdapter(arrayAdapter);
}
}