Search code examples
androidandroid-databinding

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?


Solution

  • 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 also sure that you have assigned model into DataBinding

    For ex. in your activity

    lateinit var activityMainDataBinding: ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityMainDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) 
        val dataViewModel = ViewModelProvider(this).get(DataViewModel::class.java)
        activityMainDataBinding.dataModel = dataViewModel
    }
    

    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.

    edit: Functioning demo project here. view. model.