如何删除TextChangedListener?

时间:2019-05-24 18:05:45

标签: java android textwatcher

我想使用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>

2 个答案:

答案 0 :(得分:0)

要删除监听器,您必须将其设置为 null ;我知道您正在使用Kotlin,但是在Java中将是这样的:

editText.addTextChangedListener(null);

希望有帮助!

答案 1 :(得分:0)

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

java.lang.NullPointerException: Attempt to invoke interface method 'void android.text.TextWatcher.beforeTextChanged(java.lang.CharSequence, int, int, int)' on a null object reference

您不能使用匿名类,因为您需要将其存储以删除。

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)