输入框自动提示的实现
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.it.MainActivity">
<AutoCompleteTextView
android:id="@+id/act_input"
android:hint="请输入您要搜索的内容"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="3"/>
<!--设置输入多少字符时开始进行匹配-->
</RelativeLayout>
适配器布局文件(主要对匹配内容的字体颜色等进行设置)
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="25sp"
android:textColor="#000000">
</TextView>
核心代码
package com.example.it;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends AppCompatActivity {
private AutoCompleteTextView act_input;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
act_input = (AutoCompleteTextView) findViewById(R.id.act_input);
//为输入框初始化数据
initData();
}
private void initData() {
//设置数据
String[]data = {"zhangsan","lisi","wangwu","zhaoliu"};
//设置适配器,并添加布局文件和数据
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.item,data);
//加载适配器
act_input.setAdapter(adapter);
}
}
文章评论