a6547484
a6547484

Reputation: 81

Android Architecture Components how to achieve two-way bindings for objects with ViewModel

Here is a very basic view model as such

class MainViewModel: ViewModel() {
    val text = MutableLiveData<String>()
    val person = MutableLiveData<Person>()
}

I'm trying to achieve two way binding as shown below

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@={viewModel.text}"/>

This works as expected but when it comes to binding the object:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@={viewModel.person.name}"/>

I'm getting an error: The expression viewModelPersonGetValue.getName() cannot be inverted: Two-way binding cannot resolve a setter for java.lang.String property 'name'

It appears that I am missing something, any ideas?

(I am using Android Studio 3.2 canary 1)

Upvotes: 4

Views: 1696

Answers (1)

clementiano
clementiano

Reputation: 139

This should work on Android Studio 3.1 and above as long as you don't forget to include

val binding: ActivityMainBinding = ...
binding.viewModel = viewModel 
binding.setLifecycleOwner(this) // The editText won't update without this

Upvotes: 3

Related Questions