2

I am using databinding library. I have a layout which have some edittext for getting basic user input like name, email, password etc. I want to validate these inputs inside the viewmodel on button click. I am a bit confused how to access edittext input on button click inside the view model.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="ViewModel"
        type="me.example.model.LoginViewModel"/>

 <EditText
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="13sp" />

  <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="Submit"
     android:onClick="@{() -> ViewModel.onSubmitClick()}"/>

</layout>

this is the button click method in the view model

 fun onSubmitClick(){
    Log.e("Clicked ", "True")

    }

}
Andrain
  • 872
  • 1
  • 16
  • 43

1 Answers1

1

You can reference the EditText within the Button's binding expression:

 android:onClick="@{() -> ViewModel.onSubmitClick(name.getText().toString())}"

One caveat is that snake casing becomes camel casing when doing this, so if your View's android:id is name_edit_text, you would use nameEditText.getText() within the binding expression.

Clicking the Button will then call this method in the ViewModel:

fun onSubmitClick(editTextString: String) {
    Log.d("LOG", editTextString)
}
Gavin Wright
  • 3,124
  • 3
  • 14
  • 35