ViewModel和数据绑定

9

Android 最近推出了 架构组件,其中特别包括一个ViewModel,它的设计目的是存储和管理与 UI 相关的数据,使得这些数据在屏幕旋转等配置更改时仍能保存。

Google 提供的示例中,ViewModel 的使用方式如下:

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
        });
    }
}

问题: ViewModel如何与Data Binding相关联?

我的意思是,在数据绑定的情况下,将会有一个提供UI数据的binding

它会是这个样子吗:

...
model.getUsers().observe(this, users -> {
  // update binding, that will auto-update the UI?
});
...
2个回答

2
您可以在布局xml文件中声明一个您的ViewModel类型的变量。 在您的ViewModel类中实现公共方法,通过这些方法将数据绑定到UI。
然后,您只需要在onCreate中将ViewModel设置为绑定。当您在DataBinding中设置ViewModel实例时,已经加载到ViewModel中的数据将被设置到重新创建的布局中。
如果您的布局中有一个RecyclerView,则可以在您的ViewModel类中实现一些公共方法,例如initRecyclerView(),并在设置ViewModel后在onCreate()中调用它,或者也可以通过DataBinding从ViewModel中设置适配器。

当我再次使用setValue()方法设置数据(比如在网络调用之后),数据在UI中没有反映出来。我需要像上面那样附加一个观察器吗? - Ayush P Gupta
如果您的ViewModel扩展了android.databinding中的BaseObservable,那么您可以调用notifyChange()来更新所有字段,或者调用notifyPropertyChanged(BR.yourProperty)来仅更新绑定到属性的字段。要使用第二种方法,您的公共属性或其getter应该带有@Bindable注释。您也可以使用ObservableField。更多详情,请查看https://medium.com/google-developers/android-data-binding-observability-9de4ff3fe038。 - dzikovskyy
非常感谢,我只需要将我的ViewModel扩展为Observable即可。 - Ayush P Gupta

-1

你的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;
}

9
这与用户的问题无关。他特别提到了ViewModel类。如果你已经扩展了BaseObservable类,就不能再使用ViewModel。 - HDW

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接