How to databind to onTextChanged for an EditText on Android?

后端 未结 9 1185
悲哀的现实
悲哀的现实 2020-11-30 01:41

In Yigit Boyar and George Mount\'s talk on Android Databinding they illustrate how easy it is to bind to TextWatcher\'s onTextChanged (at 13:41). O

9条回答
  •  鱼传尺愫
    2020-11-30 02:05

    1. create a class (I named him BindingAdapters). Then define your bindingAdapter methods.

      @BindingAdapter("app:textChangedListener")
      fun onTextChanged(et: EditText, number: Int) {
      et.addTextChangedListener(object : TextWatcher {
          override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
              if (et.text.toString().trim().length >= number) {
                  et.setBackgroundColor(Color.GREEN)
              }
          }
      
          override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
          override fun afterTextChanged(s: Editable) {}
      })
      

      }

    2. set this attr for editText in xml layout

        
      

提交回复
热议问题