一、创建AutoCompleteTextView
1.在布局文件中声明一个AutoCompleteTextView:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text" />
<AutoCompleteTextView android:id="@+id/actv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"/>
2.定义提示条目的样式,创建布局文件:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#000">
</TextView>
3.创建一个ArrayAdapter,用来提供数据:
autoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.actv);
List<String> list = new ArrayList<String>();
list.add("allotory");
list.add("bauble");
list.add("baobo");
list.add("album");
list.add("alow");
list.add("array");
4.为AutoCompleteTextView设置数据
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.item ,list);
autoCompleteTextView.setAdapter(arrayAdapter);
完整代码:
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text" />
<AutoCompleteTextView android:id="@+id/actv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"/>
</LinearLayout>
Item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#000">
</TextView>
AutoCompleteTextViewActivity.java
package com.android.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;
public class AutoCompleteTextViewActivity extends Activity {
private AutoCompleteTextView autoCompleteTextView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
autoCompleteTextView =
(AutoCompleteTextView)findViewById(R.id.actv);
List<String> list = new ArrayList<String>();
list.add("allotory");
list.add("bauble");
list.add("baobo");
list.add("album");
list.add("alow");
list.add("array");
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,R.layout.item ,list);
autoCompleteTextView.setAdapter(arrayAdapter);
}
}
运行结果:


本文详细介绍了如何在Android应用中创建并使用AutoCompleteTextView组件实现自动补全功能,包括布局设计、数据提供、适配器设置等关键步骤。通过实例代码演示了如何快速集成自动补全文本输入,提升用户体验。
427

被折叠的 条评论
为什么被折叠?



