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")

    }

}

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

can you show me how to get text, I'm using string and it is giving me error.
I added a toString(). See my edit. EditText#getText() returns an Editable, so that was probably causing you an issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.