1

I have one EditText in my fragment, I want to two-way binding the text value of EditText with the variable of viewModel, so that I can get this text value in viewModel to do some extra work.

ViewModel:

class MyViewModel @ViewModelInject constructor(
    private val myRepository: MyRepository,
    private val myPreferences: MyPreferences
) : ViewModel() {

    val name = myPreferences.getStoredName()

    fun buttonSubmit() {
        viewModelScope.launch(Dispatchers.IO) {
            myPreferences.setStoredName(name)
            val response = myRepository.doSomething(name)  // I can get the text value by name variable
    }
}

xml:

<layout ...>

    <data>
        <variable
            name="viewModel"
            type=".MyViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        ...>

        <EditText
            ...
            android:text="@={viewModel.name}" />  <!-- how to two-way binding name -->

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
1
  • Be aware to add the full package name including the ViewModel Name in the xml file. For example, if your ViewModel is stored in "package com.example.YOURVIEWMODELNAME" your xml type has to be "com.example.YOURVIEWMODELNAME" Commented Sep 2, 2020 at 12:15

1 Answer 1

1

You just need to define name as a MutableLiveData. So, all the text changes of the EditText are reflected to it and you'll be able to read the value in buttonSubmit like the following: (your xml content is right)

class MyViewModel @ViewModelInject constructor(
    private val myRepository: MyRepository,
    private val myPreferences: MyPreferences
) : ViewModel() {

    val name = MutableLiveData(myPreferences.getStoredName())

    fun buttonSubmit() {
        viewModelScope.launch(Dispatchers.IO) {
            myPreferences.setStoredName(name.value ?: "")
            val response = myRepository.doSomething(name.value ?: "")
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.