Search code examples
androiddata-binding

How to call Edittext onEditorAction from xml using data binding


like the below code

<data>
    <variable
      name="listener"
      type="android.view.View.OnClickListener" />
</data>


<TextView android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android: text="@ {user.firstName}"
     android:onClick="@{listener::onClick}"/>

I'm wanted to call the editorAction from XML, it is possible to perform it through xml ?.


Solution

  • 1.Create interface

    interface CustomOnEditorActionListener {
        fun onEditorAction()
    }
    

    2.BindingAdapter

    @BindingAdapter("app:customOnEditorActionListener")
    fun setCustomOnEditorActionListener(view: TextView, listener: CustomOnEditorActionListener?) {
        if (listener == null) {
            view.setOnEditorActionListener(null)
        } else {
            view.setOnEditorActionListener(object : TextView.OnEditorActionListener {
                override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                    listener.onEditorAction()
                    return false
                }
            })
        }
    }
    

    3.in XML. viewModel implemented interface CustomOnEditorActionListener

        ...
    <variable
    name="viewModel"
    type="nl.login.LoginViewModel" />
    
        ...
    <EditText
    android:id="@+id/password_edit"
    app:customOnEditorActionListener="@{viewModel}"
        ...