我正在尝试使用 AutoCompleteTextView 来实现对数据库中项目列表的搜索。当我插入第一个字符时,我能够创建一个下拉菜单,但我无法从菜单中选择一个字符并让它执行我的搜索功能。 根据开发人员参考,我创建了一个 ArrayAdapter 来处理资源。以下是我的 xml 布局 (R.layout.activity_test) 的摘录以及实现 AutoCompleteTextView 的结构。
布局活动_测试
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestActivity">
<AutoCompleteTextView
android:id="@+id/tvAutoComplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:hint="Search"
android:inputType="textAutoComplete"
android:completionThreshold="1"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
AutoCompleteTextView的实现
val itemList = ArrayList<String>()
itemList已成功采集
val autoComplete: AutoCompleteTextView = findViewById(R.id.tvAutoComplete)
val adapter = ArrayAdapter(this,R.layout.activity_test,R.id.tvAutoComplete,itemList)
autoComplete.setAdapter(adapter)
autoComplete.setOnItemClickListener { parent, view, position, id ->
Log.d("Test ", itemList[position])
}
setOnItemClickListener 不起作用。
要处理下拉菜单中项目的单击事件,请使用以下回调:
//you can use lambda instead of making an object
autoComplete.onItemClickListener = object : AdapterView.OnItemClickListener{
override fun onItemClick(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
//Handle the click event
}
}
autoComplete.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
//Handle the selection
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("invoked when the selection disappears from this view. " +
"The selection can disappear for instance when touch is " +
"activated or when the adapter becomes empty.")
}
}
您在答案中提到的事件是用于处理
AutoCompleteTextView
的点击事件,我认为它不会被调用,因为它是 EditText
的子级。在 EditText
中,不会调用点击侦听器。