使用TextWatcher获取editText的旧值

时间:2019-04-19 14:33:44

标签: mvvm kotlin textwatcher

我想使用beforeTextWatcher函数获取editText的旧值。 问题是,当我尝试获取此旧值时,返回的值始终为null,请有人帮助我

val nomTextWatcher: TextWatcher
        get() = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
                userUpdateSignup.setNom(s.toString())

            }

            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
               if(!s.toString().isEmpty())                
  userUpdateSignup.setNom(s.toString())

            }
        }

1 个答案:

答案 0 :(得分:0)

不仅不能使用TextWatcher,还必须将值存储到类属性中,然后自己检查它。

private var myFieldValue : String = ""

[...]

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

        override fun beforeTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
           userUpdateSignup.setNom(s.toString())
        }

        override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
            // Here you can check differences or what you want
            if(!s.toString().isEmpty())                
                userUpdateSignup.setNom(s.toString())

            // After text changed, you have to store it 
            myFieldValue = s.toString()
        }
    }