Saturday 16 June 2018

Say No More To TextWatcher Callback


As Android Developer, we have used TextWatcher callback to listen any of the changes in the EditText.


Something like this :
editText.addTextChangedListener(object : TextWatcher {

override fun afterTextChanged(p0: Editable?) {

}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

}
})

Data Binding Implementation


In Your xml Layout use OnTextChanged property

android:onTextChanged="@{model.onPasswordTextChanged}"


And call the view model user defined method to handle text changes in EditText. Full Snippet is below :


<EditText
android:id="@+id/password_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/username_et"
android:layout_marginTop="10dp"
android:hint="Password"
android:onTextChanged="@{model.onPasswordTextChanged}"
android:inputType="textPassword" />


ViewModel User defined method can be like this (implement as per your implementation):


fun onPasswordTextChanged(s: CharSequence,start: Int,before : Int,
count :Int){
    //TODO write your implementation here ...
}



Now no more of TextWatcher callback in your View(Activity/Fragment), Instead use data binding to avoid boilerplate code.

Use MVVM, implement user defined method’s in ViewModel to handle OnTextChanged in xml.

Hope to see more of this implementation in future :-)

Cheers!!

2 comments: