转载地址:http://blog.csdn.net/wqc_csdn/article/details/53399737
最新最新推出的MVVM架构是将MVP中的Presenter换成了View Model,也就是Model +View+ViewModel的模式。这种架构方式可以很便捷的进行数据的交互,当数据发生变化时通过ViewModel可以及时的将变化反应到View中去。
本文参考自:http://www.imooc.com/learn/719
http://www.imooc.com/learn/720
DataBinding的引入:
在需要应用DataBinding的Module的gradle文件中添加:
- 1
- 2
- 3
- 1
- 2
- 3
即可。
DataBinding的使用:
在原本的layout布局文件中将最外层的布局标签替换为:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
同时在布局文件中加入data标签,用于指定要绑定的数据类:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
修改完布局文件之后就可以在Java代码中使用DataBinding了。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Item只是自定义的一个JavaBean,里边只有Id和Content两个属性及其get和set方法
以上就是DataBinding的数据的绑定,接下来还有方法的绑定。
方法的绑定有两种情况:
-
方法引用绑定:主要是绑定一些已经原有的方法事件,例如onClick,onTextChanged这些方法
-
监听器绑定:主要是绑定一些自定义的方法事件,可以支持传入数据类型。
方法引用绑定:
自定义一个Presenter类,并在其中实现onClick,onTextChanged等需要的方法,然后在布局文件中直接声明。
在Java中实现onClick方法
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
在布局文件中直接声明方法的引用:
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
监听器绑定:
也是要先在Presenter中定义需要的方法,并定义好参数:
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
只是在布局文件中引用的时候有所不同:
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
这样就完成了监听器的绑定。