I have some data in my viewmodel which I am setting on receiving response from livedata. Can I bind this data to my UI instead of using pojo? So that whenever I change the data in my viewmodel, the UI must also change.
1 Answer
With the latest Android Studio version (3.1) available in the Beta Channel you can use LiveData Objects for databinding.
Here is a good blog post about how to use LiveData from your viewmodel for binding.
Here is also an example of mine where i used it in an fragment.
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel.class);
fragmentBinding = DataBindingUtil.inflate(inflater, R.layout.fragment,container,false);
fragmentBinding.setViewModel(viewModel);
fragmentBinding.setLifecycleOwner(this);
viewModel.getUser().observe(this, user-> {
// do whatever you want ;)
});
and in your xml you have to wrap everythin with <layout>
need to define the variables
<data>
<variable name="viewModel" type="myproject.viewmodel.MyViewModel" />
</data>
@= for two-way binding, @ for one way binding
android:text="@={viewModel.user.firstName}"
1 Comment
woodii
setLivecycleOwner is used for the ViewDataBinding (binding your ViewModel to your layout). The observe has actually nothing to do with viewbinding and is just used to listen to changes in your ViewModel.You can find further information here: developer.android.com/reference/android/databinding/…