2015年Google IO大会分布了DataBinding库,能够更快捷便利的实现MVVM结构模式。但是,通过对DataBinding的学习,其中踩过得坑,今天要在这里记录一下。对于DataBinding一些比较基础的使用,在这里就不在记录了,毕竟现在Google一下,出来很多的教程,而且,android developer官网中,也已经对其基本使用方法做了详细介绍,有英语基础的童鞋,还是去看比较官方的文章。如果英文基础不太好的,https://realm.io/cn/news/data-binding-android-boyar-mount/推荐这个博客,会有很大收获的,同时,谢谢棉花糖的这篇文章,解决了很多的疑惑。
关于配置环境:
2.0以上的 Android Studio 已经内置了对 Android Data Binding 框架的支持,配置起来也很简单,只需要在 app 的 build.gradle 文件中添加下面的内容就好了
1 dataBinding{ 2 enabled = true 3 }
但是,gradle的版本,至少得是1.5.0以上,否则配置会很麻烦。因为本人使用的Android studio版本是2.1.3,gradle也更改成了2.1.3,所以,不需要做过多的设置。但是有一点,Android studio对DataBinding的支持还不是完全的兼容,有些地方确实有点坑。
关于使用:
最近,把之前写的一个小项目,更改成了DataBinding的架构模式。感觉Android studio2.1.3版本已经很新了,但是对于一些属性的提示还不是很好,并不是完全支持的。比较基础的使用方法,在这里就不在提了,主要是写一下对ListView以及GridView的使用,还有就是对adapter的写法,以及点击跳转的事件。
首先,先是写一个ListView或者GridView的xml文件,代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <layout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:app="http://schemas.android.com/apk/res-auto"> 5 6 <data> 7 8 <variable 9 name="adapter" 10 type="android.widget.BaseAdapter"/> 11 12 </data> 13 14 <LinearLayout 15 android:layout_width="match_parent" 16 android:layout_height="match_parent" 17 android:orientation="vertical"> 18 19 <ListView 20 android:id="@+id/list_view" 21 android:layout_width="match_parent" 22 android:layout_height="match_parent" 23 app:adapter="@{adapter}"/> 24 25 </LinearLayout> 26 </layout>