gpt4 book ai didi

android - searchview不适用于自定义适配器kotlin

转载 作者:行者123 更新时间:2023-12-02 12:55:55 25 4
gpt4 key购买 nike

这是我的serachview和自定义适配器的代码。自定义适配器内部的函数未调用。没有错误,但是它不起作用,当我尝试在列表中搜索时,什么也没发生:

searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {

override fun onQueryTextChange(newText: String): Boolean {
if (TextUtils.isEmpty(newText)) {
// adapter?.filter
adapter?.filter("")
listView.clearTextFilter();
} else {
Log.i("searched ", newText)
adapter?.filter(newText);
}
return true;
}

override fun onQueryTextSubmit(query: String): Boolean {
// task HERE
return false
}

})
我的自定义适配器内部类在一个片段中:
   inner class CustomAdapter(
private val context: Context,
private val ItemDataList: List<ContactEntity>
) : BaseAdapter() {

private val inflater: LayoutInflater =
this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

override fun getCount(): Int {
return ItemDataList.size
}

override fun getItem(position: Int): Int {
return position
}

override fun getItemId(position: Int): Long {
return position.toLong()
}


override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var contact = ItemDataList[position]


val rowView = inflater.inflate(R.layout.list_item_contact, parent, false)
rowView.findViewById<TextView>(R.id.customer_name).text = contact.name
rowView.tag = position
return rowView
}


// Filter Class
fun filterCustomer(charText: String) {
Log.i("searched inside:", charText)
var charText = charText
charText = charText.toLowerCase(Locale.getDefault())
mContacts = null
if (charText.isEmpty()) {
mContacts = ItemDataList
} else {
for (contact in ItemDataList) {
if (contact.name?.toLowerCase(Locale.getDefault())?.contains(charText)!!) {
mContacts = listOf(contact)
}
}
}
notifyDataSetChanged()
}




}
这是我的xml,我在listview的上方添加了searchview:
 <SearchView
android:id="@+id/searchView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="@+id/contact_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

最佳答案

我的代码无法正常工作,因为我没有正确访问自定义适配器的方法。适配器的实例为空。
我改变了这个:

 adapter?.filter(newText);
对此:
 (listView.adapter as CustomAdapter?)?.filter(newText)
而且有效!

关于android - searchview不适用于自定义适配器kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63617150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com