4

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.

2
  • kindly elaborate as to what you want to achieve Commented Feb 21, 2018 at 12:04
  • yes, using android studio 3.1 Commented Feb 21, 2018 at 12:15

1 Answer 1

4

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}"
Sign up to request clarification or add additional context in comments.

1 Comment

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/…

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.