Home > database >  Android ViewModel two way binding is not working
Android ViewModel two way binding is not working

Time:05-31

I am trying to learn how to use MVVM, and two way data binding in Android. I am quite familiar with MVVM and two way data binding from other languages/frameworks (.net, Angular etc)

So, from what I can see, I want a viewModel to retain data, and I also want a repository that I will be passing to a service (eg to play an audio file)

I set up the View model following enter image description here

There are no exceptions, however, the bound text ("123") just does not show up in the UI.

What could I be missing here?

CodePudding user response:

You need to use DataBindingUtils to bind the view to activity instead of using setContentView.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

val binding: ActivityMainBinding = DataBindingUtil.setContentView(
        this, R.layout.activity_main)
binding.lifecycleOwner = this
binding.viewModel = viewModel [Your viewModel class object]
}

basically you need to define the viewLifecycle owner for binding and a value for the variable you created in xml file. Two way databinding is helpful in cases like EditText. In case of Radio Button or TextView etc you can simply use binding.

android:text="@{viewModel.stopColour}"

The above code snippet will work fine in case of radio Button. For more details you can visit android developer documentation link below. https://developer.android.com/topic/libraries/data-binding

CodePudding user response:

you need to init your view binding viewModel to Your activity viewModel object val activityViewModel = ViewModelProvider(this,factory).get(MainActivityViewModel::class.java)

your view binding.viewModel = activityViewModel

  • Related