//启用DataBinding
buildFeatures {
dataBinding true
}
然后点击AS右上角的Sync Now进行工程配置同步,而ViewModel不需要做什么就可以使用了。
ViewModel的优势在于生命周期和数据持久化,那么它就适用于Activity和Fragment,其次就是异步回调,不会造成内存泄漏,再次就是对View层和Model层进行隔离,是两者不存在耦合性,因此你可以知道ViewModel在整个MVVM框架中的重要性了。
① 绑定Activity
在MVVM的框架中,每一个Activity都应该对应一个ViewModel,而现在我们有一个MainActivity,因此可以新建一个viewmodels包,包下新建一个MainViewModel类,表示与MainActivity进行绑定。
public class MainViewModel extends ViewModel {
}
注意这里要继承ViewModel,虽然现在里面什么都没有的,但后面使用的时候会进行增加,下面先将我们的MainActivity与MainViewModel进行绑定。
回到MainActivity中,修改代码如下图所示;
现在我们的MainActivity和MainViewModel就绑定起来了。ViewModel是数据持久化的,因为对于一些变量就可以直接放在ViewModel当中,而不再放在Activity中,可以根据一个实际的需求来进行。
② 页面布局绘制
比如我现在有一个登录的功能要去实现,要怎么去对数据进行处理呢?
在ViewModel中定义两个变量
public String account;
public String pwd;
账号和密码这当然是最基本的两个数据了,下面我们修改一下activity_main.xml中的布局,代码如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:gravity=“center”
android:orientation=“vertical”
android:padding=“32dp”
tools:context=“.MainActivity”>
<com.google.android.material.textfield.TextInputLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”>
<com.google.android.material.textfield.TextInputEditText
android:id=“@+id/et_account”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:background=“@color/white”
android:hint=“账号” />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:layout_marginTop=“12dp”>
<com.google.android.material.textfield.TextInputEditText
android:id=“@+id/et_pwd”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:background=“@color/white”
android:hint=“密码”
android:inputType=“textPassword” />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id=“@+id/btn_login”
android:layout_width=“match_parent”
android:layout_height=“48dp”
android:layout_margin=“24dp”
android:insetTop=“0dp”
android:insetBottom=“0dp”
android:text&