Nilzor Nilzor - 11 months ago 78
Android Question

How to databind to onTextChanged for an EditText on Android?

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). On a Button. Are their slides wrong? First of all the
Button
View doesn't have an
onTextChanged
property. It neither has a
setOnTextChanged
method. Neither does
EditText
. But they both have
addTextChangedListener
which takes a
TextWatcher
as input.

So what are they talking about? How do they do it? Their example code does not compile, but gives this error:

Error:(17) No resource identifier found for attribute 'onTextChanged' in package 'android'


How do I bind to a "Text Changed Event" on any View, or EditText in particular, with the Android Databinding framework?

Answer Source

Actually it works out of the box. I think my mistake was using an old version of the data binding framework. Using the latest, this is the procedure:

View:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/username"
    android:text="Enter username:"
    android:onTextChanged="@{data.onTextChanged}" />

Model:

public void onTextChanged(CharSequence s, int start, int before, int count) {
    Log.w("tag", "onTextChanged " + s);
}

Make sure you are referncing gradle build tools v1.5.0 or higher and have enabled databinding with android.dataBinding.enabled true in your build.gradle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download