Android MVVM框架模式介绍

为什么使用MVVM?

  • 实现视图和逻辑代码的解耦

  • 大大的简化了代码

  • 修改XML中的控件时java代码不需要修改

  • 迭代更新UI时,一般只需要更新XML

  • 可复用性,一个viewmodel复用到多个view中,即同一份数据用不同的view来展示

  • 提高布局文件的解析速度

    findViewById--->注解框架====>注解框架虽然简便一些,但效率总是低于findViewById

    so----------------------->DataBinding

MVVM核心

​ DataBinding

使用

  • 配置gradle
    android {
    dataBinding {
    enabled true
    }
    }

  • XML中<layout>作为根节点,通过<data>节点引入我们要使用的数据源

       <data>
          <variable
              name="user"
              type="com.example.aron.UserEntity" >
          </variable>
       </data>
    

另一种写法:

<data>
    <import type="com.example.aron.UserEntity"/>
    <variable
        name="user"
        type="UserEntity" >
    </variable>
</data>

设置别名:

<import type="com.example.aron.UserEntity" alias="custom"/>
  • 绑定流程

       ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    
      <TextView
          android:text="@{user.userName}"/>
    
    
      binding.setUser(UserEntity)
    

    注意:ActivityMainBinding是根据xml自动生成的,名字即为xml去掉下划线的名字,它会在xml布局最外层添加<layout></layout>后自动生成,如果没有生成Rebuild Project。

  • 用法

    • 支持基本的三目运算,例:(android:text="@{user.username??user.nickname}")
    • 字符拼接,例:(android:text="@{username is :+user.username}")
    • 类型转换,例:(android:text="@{String.valueOf(user.age)}")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。