ViewModel and data binding

Android recently introduced Architecture Components and, in particular, ViewModel , which

designed to store and manage data associated with the user interface, so that the data saves configuration changes, such as screen shielding

In the example provided by Google, ViewModel is used as follows:

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

Question: What does the ViewModel look like for correlation with data binding ?

I mean that in the case of data binding there will be bindingone that provides data for the user interface.

Would it look like this:

...
model.getUsers().observe(this, users -> {
  // update binding, that will auto-update the UI?
});
...
+4
source share
2 answers

viewmodel XML . viewmodel , ui.

onCreate. , , viewmodel, .

, , - , initRecyclerView(), onCreate() databinding .

+3

layout_name.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools">

   <data>
       <import type="android.view.View"/>
       <variable
           name="model"
           type="com.yourpackage.ViewModelName"/>
   </data>

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@color/white"
       android:visibility="@{model.someVariable == true ? View.VISIBLE : View.GONE}">

   </RelativeLayout>
</layout>

Activity

public class YourActivityName extends BaseActivity
{
    private ViewModelName viewModelVariable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewModelName viewModelVariable = new ViewModelName(); 
        ViewDataBinding viewDataBinding = DataBindingUtil.setContentView(this, R.layout.layout_name);
        viewDataBinding.setVariable(BR.model, viewModelVariable);

    }
}

ViewModel

public class ViewModelName extends BaseObservable{
    //Logic and variables for view model
    public boolean someVariable;
}
+2

Source: https://habr.com/ru/post/1678812/


All Articles