1

I am using data binding, I am trying to create a class with the values when the user fills up multiple edit texts, also with some validations.

the class is something like

data class Person(
    var name: String,
    var age: Int,
    var email: String
)

The view model variable,

val person: MutableLiveData<Person> by lazy { MutableLiveData<Person>()}

The template

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:text="@{viewModel.person.name}" />
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:text="@{viewModel.person.age}" />
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textEmailAddress"
    android:text="@{viewModel.person.email}" />

with the click on button, I am trying to print out the object,

binding.savebtn.setOnClickListener {
    Log.d("debug", "${viewModel.person.value}:")
}

and it prints out D/debug: null:

I am trying to create a room entity after validation. How can I make this work?

  • This is what you are looking for, [Two way data binding](https://stackoverflow.com/questions/38982604/two-way-databinding-in-edittext) – rahat Jan 11 '21 at 18:12
  • Check out the answer below, I hope you will appreciate the effort. – rahat Jan 26 '21 at 17:44

1 Answers1

0

You can do it this way

val person: Person by lazy { Person("","","")}

and then in the onclicklistener

binding.savebtn.setOnClickListener {
    Log.d("debug", "${viewModel.person.name},${viewModel.person.email}")
}

You will get the values, but the issue is, when you change the value in model it wont be reflected in the EditText, since these are plain String objects not livedata or ObservableField.

Let's you do, viewModel.person.name="custom name" it wont change the text in EditText. If you target to only get the typed text into the model directly, then this will do it for you.

rahat
  • 1,840
  • 11
  • 24