当前位置:网站首页>学习MVVM笔记(一)
学习MVVM笔记(一)
2022-07-05 04:06:00 【一禅-小和尚】
MVVM
model :数据层,包含数据实体和对数据实体的操作
View :界面层,对应Activity XML view 负责数据显示以及用户交互
ViewModel :关联层 将model 和view 进行绑定,model或者View 更改时,实时刷新对方
注意:
1.View只做和UI相关的工作,不涉及任何业务逻辑,不涉及操作数据,不处理数据。UI和数据严格的分开
2.ViewModel只做和业务逻辑相关的工作,不涉及任何和UI相关的操作,不持有控件引用,不更新UI。
DataBinding 是谷歌官方推荐的一个库,DataBinding 库来写声明的layouts文件,可以用最少的代码来绑定你的app逻辑和layouts文件 ,DataBinding是一个support库
(1)搭建环境
在app的build.gradle文件中添加
android {
.... dataBinding {
enabled = true } }
(2)编写layout文件
起始标签是layout,接下来是data元素一个view元素,这个view元素就是没有使用DataBinding的layout文件的根元素
在data内描述一个name的变量属性,使其可以在layout中使用,type为绑定的data对象
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.example.mvvmdemo.User" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_name"
android:text="@{user.mUserName}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_age"
android:text='@{
user.mUserage + ""}'
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
data对象:
package com.example.mvvmdemo;
public class User {
public final String mUserName;
public final int mUserage;
public User(String userName, int userAge) {
this.mUserName = userName;
mUserage = userAge;
}
}
(3)Binding数据
默认情况下,一个Binding类会基于layout文件的名称而产生,将其转换成(首字母大写的命名规范,并加Binding后缀) ,上述的layout文件是activity_main.xml ,因此生成的类名是ActivityMainBinding。此类包含从layout属性到layout的views中的所有bindings(包括user变量) ,而且还知道怎么给Binding表达式分配值,创建bindings的最简单的inflating(layout文件和Activity/Fragment的链接)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
User user = new User("haha" , 22);
binding.setUser(user);
}
}
**如果在ListView 或者RecyclerView adapter使用DataBinding时,会使用
**
ListItemBinding binding = ListItemBinding.inflate(layoutInflater, viewGroup, false); //or
ListItemBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false);
还需要注意的是:如果将User类中的变量改成私有的会报错的。
Found data binding errors. ****/ data binding error ****msg:Could not find accessor demo.com.databindingdemo.User.mUserName
(4)事件处理
数据绑定允许编写表达式来处理view分派的事件,事件属性名字取决于监听器方法名字。
public class MyHandler {
public void myOnClick(View view){
Toast.makeText(view.getContext(),"hello",Toast.LENGTH_SHORT).show();
}
public boolean myOnLongClick(View view){
Toast.makeText(view.getContext(),"hello world",Toast.LENGTH_SHORT).show();
return true;
}
}
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="handlers" type="com.heyy.databingexample.MyHandler"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试事件绑定"
android:onClick="@{handlers::myOnClick}"
android:onLongClick="@{handlers::myOnLongClick}"/>
</LinearLayout>
</layout>
(5)深入DataBinding用法
import :零个或者多个import元素可能在data元素中使用,这些只用在你的layout文件中添加引用
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.example.mvvmdemo.User" />
<import type="android.view.View"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_name"
android:text="@{user.mUserName}"
android:visibility="@{user.mUserage == 22 ? View.VISIBLE : View.GONE}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_age"
android:text='@{
user.mUserage + ""}'/>
当类名有冲突时,可以使用alias重新命名
<import type="android.view.View"
alias="test"/>
android:visibility="@{user.mUserage == 22 ? test.VISIBLE : test.GONE}"
导入的类型还可以在表达式中使用static属性和用法
public class StringUtls {
public static String translateStr(String str){
return str+"haha";
}
}
<import type="com.example.mvvmdemo.StringUtls"/>
android:text="@{StringUtls.translateStr(user.mUserName)}"
(6)Data对象
DataBinging 允许我们创建可观察的对象,字段和集合,当我们数据发生改变时,要通知其他的对象就可以使用DataBinding
Observable对象
实现android.databinding.Observable接口的类可以允许附加一个监听器到Bound对象,以便监听对象上的所有属性的变化。
一个BaseObervabke的基类为实现监听器注册机制而创建。
public void setmUserName(String mUserName) {
this.mUserName = mUserName;
notifyPropertyChanged(BR.user);
}
Observable 集合
Oberservable集合允许控件访问这些data对象,ObservableArraMap 用于键是引用类型,如string
ObservableArrayMap<String, Object> user = new ObservableArrayMap<>(); user.put("name", "Jack"); user.put("age", 17);
<data>
<import type="android.databinding.ObservableMap"/>
<variable name="user" type="ObservableMap<String, Object>"/> </data>
<TextView
android:text='@{
user["name"]}'
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:text='@{
String.valueOf(1 + (Integer)user["age"])}'
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Observable 字段
ObservableFields是包含具有单个字段的Observable对象。
<data>
<variable
name="itemViewModel"
type="com.autoai.project.home.viewmodel.AppItemViewModel" />
</data>
使用
android:text="@{itemViewModel.appTitle}"
类
public class AppItemViewModel {
public ObservableField<String> appTitle = new ObservableField<>();
}
边栏推荐
- Technical tutorial: how to use easydss to push live streaming to qiniu cloud?
- Differences among 10 addressing modes
- CTF stegano practice stegano 9
- Use Firefox browser to quickly pick up Web image materials
- @The problem of cross database query invalidation caused by transactional annotation
- 优先使用对象组合,而不是类继承
- Redis source code analysis: redis cluster
- 长度为n的入栈顺序的可能出栈顺序
- Deflocculant aminoiodotide eye drops
- UI自动化测试从此告别手动下载浏览器驱动
猜你喜欢
laravel8 导出Excle文件
[C language] address book - dynamic and static implementation
Deep learning - LSTM Foundation
官宣!第三届云原生编程挑战赛正式启动!
Interview summary: This is a comprehensive & detailed Android interview guide
Containerd series - detailed explanation of plugins
An elegant program for Euclid‘s algorithm
快手、抖音、视频号交战内容付费
面试字节,过关斩将直接干到 3 面,结果找了个架构师来吊打我?
Web components series (VII) -- life cycle of custom components
随机推荐
Operation flow of UE4 DMX and grandma2 onpc 3.1.2.5
A real day for Beijing programmers!!!!!
Is "golden nine and silver ten" the best time to find a job? Not necessarily
kubernetes集群之调度系统
Three level linkage demo of uniapp uview u-picker components
Online sql to excel (xls/xlsx) tool
Rome chain analysis
Interview summary: This is a comprehensive & detailed Android interview guide
ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
C语言课设:影院售票管理系统
MindFusion. Virtual Keyboard for WPF
输入的查询SQL语句,是如何执行的?
[array]566 Reshape the matrix - simple
An elegant program for Euclid‘s algorithm
Basic function learning 02
线上故障突突突?如何紧急诊断、排查与恢复
UI automation test farewell to manual download of browser driver
laravel8 导出Excle文件
Use Firefox browser to quickly pick up Web image materials
Rust blockchain development - signature encryption and private key public key