gpt4 book ai didi

java - 如何删除TextChangedListener?

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:48 26 4
gpt4 key购买 nike

我想使用 EditText 在数据库中搜索,然后将项目添加到 RecylerView。现在我可以只搜索一个项目,项目显示,更改编辑文本后它消失,我希望它保留,我希望我搜索的每个项目都自动添加到 RecyclerView。所以我想我可以删除ChangeTextListener,然后再次添加它来搜索另一个项目,依此类推(?)

在MainActivity.kt中

fun Threads() {
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(
s: CharSequence, start: Int,
count: Int, after: Int
) {
}

override fun onTextChanged(
s: CharSequence, start: Int,
before: Int, count: Int
) {
Thread {
//here we search for item
val itemsList = db?.costDAO()!!.getByName(s.toString())

runOnUiThread {
//here we pass item to Adapter constructor
recyclerView.adapter = MyAdapter(this@MainActivity, itemsList)
adapter.notifyDataSetChanged()

}
}.start()
}

override fun afterTextChanged(s: Editable) { }

成本.DAO

@Dao
interface CostDAO {

@Query("select * from cost where name like :name")
fun getByName(name : String) : List<Cost>

最佳答案

罗伯特的回答不正确。这将导致崩溃

java.lang.NullPointerException:尝试在空对象引用上调用接口(interface)方法“void android.text.TextWatcher.beforeTextChanged(java.lang.CharSequence, int, int, int)”

您不能使用匿名类,因为您需要存储它才能删除。

val textWatcher = object :TextWatcher {
override fun afterTextChanged(s: Editable?) {}

override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {}

override fun onTextChanged(
s: CharSequence?,
start: Int,
before: Int,
count: Int
) {
//Do stuff
}

}
binding.etEmail.addTextChangedWatcher(textWatcher)
// do what you need to do and later on
// ...
//
binding.etEmail.removeTextChangeWatcher(textWatcher)

关于java - 如何删除TextChangedListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56297620/

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