BindingAdapter的原理
一般我们在布局文件里用到的控件的各种属性,在源码里面都会有它对应的set和get方法,并且也会定义好需要的参数类型,这样我们一旦设置好相应的属性之后代码就自动去匹配对应的set和get方法进行属性设置,而我们有时候也会用到源码里没有定义好的属性,这样方便布局展示,这样就可以用BindingAdapter来解决这个问题。它的作用就是可以让我们自己定义想要用到的属性,然后给这个属性设置set方法设置到页面中显示
databinding中自定义属性依赖于注解 @BindingAdapter
1.作用于方法(和类无关,这个自定义属性的方法可以写在任何地方)
2.它定义了xml的属性赋值的java实现(注解的方法中就是我们对这个控件进行处理)
3.方法必须为公共静(public static)方法,可以有一到多个参数。
当某些属性需要自定义处理逻辑的时候可以使用 BindingAdapter,比如我们可以使用 BindingAdapter 重新定义 TextView 的 setText 方法,让输入的英文全部转换为小写,自定义 TextViewAdapter 如下:
- /**
- * 自定义BindingAdapters
- * Powered by jzman.
- * Created on 2018/12/6 0006.
- */
- public class TextViewAdapter {
-
- @BindingAdapter("android:text")
- public static void setText(TextView view, CharSequence text) {
- //省略特殊处理...
- String txt = text.toString().toLowerCase();
- view.setText(txt);
- }
- }
此时,当我们使用 databinding 的优先使用我们自己定义的 BindingAdapter,可能会疑惑为什么能够识别呢,在编译期间 data-binding 编译器会查找带有 @BindingAdapter 注解的方法,最终会将自定义的 setter 方法生成到与之对应的 binding 类中,生成的部分代码如下:
- @Override
- protected void executeBindings() {
- long dirtyFlags = 0;
- synchronized(this) {
- dirtyFlags = mDirtyFlags;
- mDirtyFlags = 0;
- }
- // batch finished
- if ((dirtyFlags & 0x2L) != 0) {
- // api target 1
- //注意:这里是自定义的TextViewAdapter
- com.manu.databindsample.activity.bindingmethods.TextViewAdapter.setText(this.tvData, "这是TextView");
- }
- }
下面以案例的形式验证一下 BindingAdapter 的使用,创建布局文件如下:
- <layout xmlns:android="http://schemas.android.com/apk/res/android">
- <data> 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:background="#a37c7c"
- android:text="这是TextView..."
- android:textSize="16sp" />
-
- <TextView
- android:id="@+id/tvData"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="10dp"
- android:background="#a37c7c"
- android:text="@{`这是TextView...`}"
- android:textSize="16sp" />
- LinearLayout>
- layout>
使用自定义的 BindingAdapter 效果如下:

可知,自定义的 TextViewAdapter 生效了,可以根据需求很方便对一下数据进行预特殊处理,这也是 BindingAdapter 的作用。
自定义属性设置
自定义属性设置可以定义单个属性也可以定义多个属性,先来定义单个属性,参考如下:
- /**
- * 自定义BindingAdapters
- * Powered by jzman.
- * Created on 2018/12/7 0007.
- */
- public class ImageViewAdapter {
- /**
- * 定义单个属性
- * @param view
- * @param url
- */
- @BindingAdapter("imageUrl")
- public static void setImageUrl(ImageView view, String url) {
- Glide.with(view).load(url).into(view);
- }
- }
此时我们可以在布局文件中使用自定义属性 imageUrl 了,使用参考如下:
- <layout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto">
- <data> data>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:gravity="center_horizontal">
-
- <ImageView
- android:layout_width="100dp"
- android:layout_height="100dp"
- app:imageUrl="@{`https://goss.veer.com/creative/vcg/veer/800water/veer-136599950.jpg`}"/>
- LinearLayout>
- layout>
上述代码测试效果如下:

这样就可以很方便的使用 imageUrl 属性来加载网络图片了,这里不要担心线程切换问题,databinding 库会自动完成线程切换,那么如何自定义多个属性呢。
下面自定义多个属性,定义方式参考如下:
- /**
- * 自定义BindingAdapters
- * Powered by jzman.
- * Created on 2018/12/7 0007.
- */
- public class ImageViewAdapter {
- /**
- * 定义多个属性
- * @param view
- * @param url
- * @param placeholder
- * @param error
- */
- @BindingAdapter(value = {"imageUrl", "placeholder", "error"})
- public static void loadImage(ImageView view, String url, Drawable placeholder, Drawable error) {
- RequestOptions options = new RequestOptions();
- options.placeholder(placeholder);
- options.error(error);
- Glide.with(view).load(url).apply(options).into(view);
- }
- }
此时,可在布局文件中使用上面定义的三个属性了,即 imageUrl、placeholder、error,使用方式参考如下:
- <layout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto">
- <data> data>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:gravity="center_horizontal">
-
- <ImageView
- android:layout_width="100dp"
- android:layout_height="100dp"
- android:layout_marginTop="10dp"
- app:imageUrl="@{`https://goss.veer.com/creative/vcg/veer/800water/veer-136599950.jpg`}"
- app:placeholder="@{@drawable/icon}"
- app:error="@{@drawable/error}"/>
- LinearLayout>
- layout>
此时,三个属性全部使用才能 BindingAdapter 才能正常工作,如果使用了其中的一些属性则不能正常编译通过,那么如何在自定义多个属性而正常使用其中的部分属性呢,@BindingAdapter 注解还有一个参数 requireAll ,requireAll 默认为 true,表示必须使用全部属性,将其设置为 false 就可以正常使用部分属性了,此时,自定义多个属性时要配置 注解 @BindAdapter 的 requireAll 属性为 false,参考如下:
- // requireAll = false
- @BindingAdapter(value = {"imageUrl", "placeholder", "error"},requireAll = false)
- public static void loadImage(ImageView view, String url, Drawable placeholder, Drawable error) {
- RequestOptions options = new RequestOptions();
- options.placeholder(placeholder);
- options.error(error);
- Glide.with(view).load(url).apply(options).into(view);
- }
-
此时,布局文件就可以使用部分属性了,如下面布局文件只使用 imageUrl 和 placeholder 也不会出现编译错误:
-
- android:layout_width="100dp"
- android:layout_height="100dp"
- android:layout_marginTop="10dp"
- app:imageUrl="@{`https://goss.veer.com/creative/vcg/veer/800water/veer-136599950.jpg`}"
- app:placeholder="@{@drawable/icon}"/>
再来一个例子,
Android扩大View点击区域
开发过程中经常会遇到如下这种场景,对于CheckBox而言,整体较小,然后为了用户体验--“好点”,往往需要扩大点击区域。通常的做法就是给CheckBox增加Padding以达到扩大点击区域的目的,但是为了对齐UI,往往需要一通计算跟调整才能“如愿以偿”,可谓哭笑不得。那怎么样可以优雅的解决这个问题呢?
image.png
可以配合BindingAdapter实现在xml上的直接处理。BindgingAdapter定义如下:
- @BindingAdapter("expandTouchArea")
- fun expandTouchArea(view: View, size: String) {
- view.postDelayed({
- val bounds = Rect()
- view.getHitRect(bounds)
- var left = 0
- var top = 0
- var right = 0
- var bottom = 0
- /*
- * size 举例 `2` or `2 4` or `2 4 6 8`
- */
- val mSize = size.trim()
- val ss = mSize.split(" ")
- when (ss.size) {
- 1 -> {
- val sdp = (ss[0].toIntOrNull() ?: 0).idp()
- left = sdp
- top = sdp
- right = sdp
- bottom = sdp
- }
- 2 -> {
- val sdp = (ss[0].toIntOrNull() ?: 0).idp()
- val sdp1 = (ss[1].toIntOrNull() ?: 0).idp()
- left = sdp
- top = sdp1
- right = sdp
- bottom = sdp1
- }
- 4 -> {
- left = (ss[0].toIntOrNull() ?: 0).idp()
- top = (ss[1].toIntOrNull() ?: 0).idp()
- right = (ss[2].toIntOrNull() ?: 0).idp()
- bottom = (ss[3].toIntOrNull() ?: 0).idp()
- }
- else -> {
- return@postDelayed
- }
- }
- bounds.left -= left
- bounds.top -= top
- bounds.right += right
- bounds.bottom += bottom
- val mTouchDelegate = TouchDelegate(bounds, view);
- val p = view.parent
- if (p is ViewGroup) {
- p.touchDelegate = mTouchDelegate;
- }
- }, 100)
- }
其中idp()是dp转px的转换函数(Kotlin扩展),实际使用时请替换
使用示例:
- android:layout_width="14dp"
- android:layout_height="14dp"
- android:background="@drawable/ic_cb_common"
- android:button="@null"
- android:checked="false"
- app:expandTouchArea="@{`20 10 50 20`}"/>
参数解析
- //表示在View原有范围的基础上在四周增加20dp的区域
- app:expandTouchArea="@{`20`}
- //表示在View原有范围的基础上左右增加20dp, 上下增加10dp的区域
- app:expandTouchArea="@{`20 10`}
- //表示在View原有范围的基础上, 左上右下分别增加20dp 10dp 50dp 20dp的区域
- app:expandTouchArea="@{`20 10 50 20`}
2.4、注意事项
1、若View的自定义触摸范围超出View.parent的大小,则超出的那部分无效。
2、一个ViewGroup里只能设置一个,设置多个时只有最后设置的那个有效。(也可以多个,需要自定义ViewGroup)
3、只有设置那个View的View.parent接收到点击事件时才能触发,也就是说这个区域是可以被其他View遮挡的,so被遮挡时也无效。
BindingAdapter 的介绍到此为止。
参考内容:
@BindingAdapter使用小结_执 卓的博客-CSDN博客_bindingadapter
Android Jetpack组件之BindingAdapter详解_躬行之的博客-CSDN博客_bindingadapter
https://www.jianshu.com/p/fe709bfffe9c
https://www.jianshu.com/p/8d3648909b0d
我试了都不起作用,也没有报错。 java也不起作用啊。鸡肋!朋友们如果试验成功交流一下啊。
-
相关阅读:
网络通信及TCP/IP协议
如何实现Laravel 5.1 分页功能及自定义分页样式
免费分享一套SpringBoot+Vue自习室(预约)管理系统,帅呆了~~
【毕业设计】基于php+mysql的社区交流网站设计与实现(毕业论文+程序源码)——社区交流网站
_sys_exit()函数的以及semihosting半主机模式的说明
day09-Tomcat01
Java 17的这些新特性,Java迈入新时代
Linux下platform驱动框架描述
三、N元语法(N-gram)
36. 干货系列从零用Rust编写负载均衡及代理,内网穿透中内网代理的实现
-
原文地址:https://blog.csdn.net/nnmmbb/article/details/126284594