Yadynesh Desai
Yadynesh Desai

Reputation: 231

Can I use data binding to bind UI with data in my viewmodel?

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.

Upvotes: 4

Views: 3821

Answers (1)

woodii
woodii

Reputation: 793

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}"

Upvotes: 4

Related Questions