Reputation: 392
So I have a list of product in my recyclerview
. Have a editText
for search term .
Each time user type something in the editText
field the list must be filtered .
with live search there is no problem and the process work well .
for better ui experience I created a button(btn_search
) for the edittext also. But in this case when click on the button the list not filtered and just disappeared .!!!
what is wrong with my code.
Code :
this is function in the adapter that calls datachanged :
ListAdapter :
fun filterList(filtername : List<Model>) {
this.model = filtername
notifyDataSetChanged()
}
activity :
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?, p1: Int, p2: Int, 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)
}
So any idea where I'm doing wrong ?
Upvotes: 0
Views: 332
Reputation: 1711
Seems like you are not getting the EditText
text, you are casting the EditText
directly into string in this line
button.setOnClickListener {
filter(editText.toString())
}
So, you need to change it to this
button.setOnClickListener {
filter(editText.text.toString())
}
Upvotes: 3