业务场景:
最近在开发一款Android app,需要在输入字符后,自动搜索相关的匹配项,然后展示为下拉列表,从列表中选择需要的条目后,填充到对应的文本框
解决方案:
我采用的 AutoCompleteTextView 组件来实现
代码如下:
layout代码:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/goodsName"
android:textSize="20dp"
android:textAlignment="center"
android:layout_weight="3"/>
<AutoCompleteTextView
android:id="@+id/goodsName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="7"
android:hint="请输入"/>
</LinearLayout>
// 定义适配器和下拉列表数据源
// 定义Adapter
val goodsData = arrayListOf<String>()
// 定义适配器
val adapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, goodsData)
binding.goodsName.setAdapter(adapter)
var goodsList:List<Goods> = emptyList()
// 定义文本改变事件
// 字符改变事件发生在条目点击事件之前
binding.goodsName.doOnTextChanged { goodsName, start, before, count ->
goodsData.clear()
goodsList = goodsService.findGoodsList(goodsName)
goodsList.forEach {
goodsData.add(it.name)
}
}
// 定义条目点击事件
binding.goodsName.setOnItemClickListener { _, _, _, _ ->
// 定义你需要的操作
}
最终效果: