Android MVVM框架搭建(一)ViewModel + LiveData + DataBinding

//启用DataBinding

buildFeatures {

dataBinding true

}

然后点击AS右上角的Sync Now进行工程配置同步,而ViewModel不需要做什么就可以使用了。

二、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&

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值