如何解决在RecyclerView中过滤产品列表-Android
因此,我的recyclerview
中有一个产品列表。为搜索词添加editText
。
每次用户在editText
字段中键入内容时,都必须过滤列表。
使用实时搜索没有问题,并且该过程运行良好。
为了获得更好的ui体验,我还为edittext创建了一个按钮(btn_search
)。但是在这种情况下,当单击按钮时,列表没有被过滤,而是消失了。
我的代码有什么问题。
代码:
这是适配器中调用datachanged的函数:
ListAdapter :
fun filterList(filtername : List<Model>) {
this.model = filtername
notifyDataSetChanged()
}
活动:
lateinit var editText: EditText
lateinit var model: ArrayList<Model>
lateinit var adapter: ListAdapter
lateinit var button: Button
lateinit var recyclerView: RecyclerView
button = findViewById(R.id.btn_search)
var list = ArrayList<Model>()
list.add(somedata) ...
recyclerView = findViewById(R.id.recyclerView)
model = list
recyclerView.layoutManager = GridLayoutManager(this@MainActivity,2)
adapter = ListAadapter(model)
recyclerView.adapter = adapter
editText = findViewById(R.id.edit_text_search)
// this is where call btnsearch but the list not filtered and disappeared
button.setOnClickListener {
filter(editText.toString())
}
// with this live search there is no issue and list filtered
/*
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(text: Editable?) {
filter(text.toString())
}
override fun beforeTextChanged(p0: CharSequence?,p1: Int,p2: Int,p3: Int) {
}
override fun onTextChanged(p0: CharSequence?,p3: Int) {
}
})*/
// this is the function for filter the list
fun filter(text: String) {
val filterNameList = ArrayList<Model>()
model.filterTo(filterNameList) { model ->
model.title.contains(text)
}
adapter.filterList(filterNameList)
}
那么我在哪里做错了吗?
解决方法
似乎您没有得到EditText
文本,您是在这一行中将EditText
直接转换为字符串
button.setOnClickListener {
filter(editText.toString())
}
因此,您需要将其更改为此
button.setOnClickListener {
filter(editText.text.toString())
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。