Android自动补全

首先,主页面的xml文件中添加一个AutoCompleteTextView组件,简单设置属性。代码如下:

<AutoCompleteTextView
        android:id="@+id/actvId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        android:inputType="text" />

为应用添加一个item组件,显示可选择的待选项,代码如下:

<?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:textColor="#000"
    android:padding="10dp" >

</TextView>

下来,开始写Oncreat()的函数代码:

//在全局变量中声明AutoCompleteTextView组件及要添加的数据源和对应的Adapter
   private AutoCompleteTextView actv;
    private List<String> datas;
    private ArrayAdapter<String> adapter;
    //以下代码放在Oncreat()函数中
    //找到AutoCompleteTextView组件
    actv = (AutoCompleteTextView) findViewById(R.id.actvId);
    //填充datas数据,随机产生50个长度为10的字符串
datas = new ArrayList<>();
for (int i = 0; i < 50; i++) {
    char[] chars = new char[10];
    for (int j = 0; j < chars.length; j++) {
        chars[j] = (char) ((int) (Math.random() * 25) + 'a');
    }
        datas.add(new String(chars));
        }
        //设置adapter
adapter=new ArrayAdapter<>(getApplicationContext(), R.layout.item_word,datas);
actv.setAdapter(adapter);
    }

运行界面如下:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值