• Android一个有用又有趣的知识点:BindingAdapter


     BindingAdapter的原理


      一般我们在布局文件里用到的控件的各种属性,在源码里面都会有它对应的set和get方法,并且也会定义好需要的参数类型,这样我们一旦设置好相应的属性之后代码就自动去匹配对应的set和get方法进行属性设置,而我们有时候也会用到源码里没有定义好的属性,这样方便布局展示,这样就可以用BindingAdapter来解决这个问题。它的作用就是可以让我们自己定义想要用到的属性,然后给这个属性设置set方法设置到页面中显示

    databinding中自定义属性依赖于注解 @BindingAdapter

    1.作用于方法(和类无关,这个自定义属性的方法可以写在任何地方)
    2.它定义了xml的属性赋值的java实现(注解的方法中就是我们对这个控件进行处理)
    3.方法必须为公共静(public static)方法,可以有一到多个参数。
     


    当某些属性需要自定义处理逻辑的时候可以使用 BindingAdapter,比如我们可以使用 BindingAdapter 重新定义 TextView 的 setText 方法,让输入的英文全部转换为小写,自定义 TextViewAdapter 如下:

    1. /**
    2.  * 自定义BindingAdapters
    3.  * Powered by jzman.
    4.  * Created on 2018/12/6 0006.
    5.  */
    6. public class TextViewAdapter {
    7.     @BindingAdapter("android:text")
    8.     public static void setText(TextView view, CharSequence text) {
    9.         //省略特殊处理...
    10.         String txt = text.toString().toLowerCase();
    11.         view.setText(txt);
    12.     }
    13. }


    此时,当我们使用 databinding 的优先使用我们自己定义的 BindingAdapter,可能会疑惑为什么能够识别呢,在编译期间 data-binding 编译器会查找带有 @BindingAdapter 注解的方法,最终会将自定义的 setter 方法生成到与之对应的 binding 类中,生成的部分代码如下:

    1. @Override
    2. protected void executeBindings() {
    3.     long dirtyFlags = 0;
    4.     synchronized(this) {
    5.         dirtyFlags = mDirtyFlags;
    6.         mDirtyFlags = 0;
    7.     }
    8.     // batch finished
    9.     if ((dirtyFlags & 0x2L) != 0) {
    10.         // api target 1
    11.         //注意:这里是自定义的TextViewAdapter
    12.         com.manu.databindsample.activity.bindingmethods.TextViewAdapter.setText(this.tvData, "这是TextView");
    13.     }
    14. }


    下面以案例的形式验证一下 BindingAdapter 的使用,创建布局文件如下:

    1. <layout xmlns:android="http://schemas.android.com/apk/res/android">
    2.     <data> data>
    3.     <LinearLayout
    4.         android:layout_width="match_parent"
    5.         android:layout_height="match_parent"
    6.         android:orientation="vertical">
    7.        
    8.         <TextView
    9.             android:layout_width="wrap_content"
    10.             android:layout_height="wrap_content"
    11.             android:background="#a37c7c"
    12.             android:text="这是TextView..."
    13.             android:textSize="16sp" />
    14.        
    15.         <TextView
    16.             android:id="@+id/tvData"
    17.             android:layout_width="wrap_content"
    18.             android:layout_height="wrap_content"
    19.             android:layout_marginTop="10dp"
    20.             android:background="#a37c7c"
    21.             android:text="@{`这是TextView...`}"
    22.             android:textSize="16sp" />
    23.     LinearLayout>
    24. layout>


    使用自定义的 BindingAdapter 效果如下:

    可知,自定义的 TextViewAdapter 生效了,可以根据需求很方便对一下数据进行预特殊处理,这也是 BindingAdapter 的作用。

    自定义属性设置
    自定义属性设置可以定义单个属性也可以定义多个属性,先来定义单个属性,参考如下:

    1. /**
    2.  * 自定义BindingAdapters
    3.  * Powered by jzman.
    4.  * Created on 2018/12/7 0007.
    5.  */
    6. public class ImageViewAdapter {
    7.     /**
    8.      * 定义单个属性
    9.      * @param view
    10.      * @param url
    11.      */
    12.     @BindingAdapter("imageUrl")
    13.     public static void setImageUrl(ImageView view, String url) {
    14.         Glide.with(view).load(url).into(view);
    15.     }
    16. }


    此时我们可以在布局文件中使用自定义属性 imageUrl 了,使用参考如下:

    1. <layout xmlns:android="http://schemas.android.com/apk/res/android"
    2.     xmlns:app="http://schemas.android.com/apk/res-auto">
    3.     <data> data>
    4.     <LinearLayout
    5.         android:layout_width="match_parent"
    6.         android:layout_height="match_parent"
    7.         android:orientation="vertical"
    8.         android:gravity="center_horizontal">
    9.        
    10.         <ImageView
    11.             android:layout_width="100dp"
    12.             android:layout_height="100dp"
    13.             app:imageUrl="@{`https://goss.veer.com/creative/vcg/veer/800water/veer-136599950.jpg`}"/>
    14.     LinearLayout>
    15. layout>


    上述代码测试效果如下:

    这样就可以很方便的使用 imageUrl 属性来加载网络图片了,这里不要担心线程切换问题,databinding 库会自动完成线程切换,那么如何自定义多个属性呢。

    下面自定义多个属性,定义方式参考如下:

    1. /**
    2.  * 自定义BindingAdapters
    3.  * Powered by jzman.
    4.  * Created on 2018/12/7 0007.
    5.  */
    6. public class ImageViewAdapter {
    7.     /**
    8.      * 定义多个属性
    9.      * @param view
    10.      * @param url
    11.      * @param placeholder
    12.      * @param error
    13.      */
    14.     @BindingAdapter(value = {"imageUrl", "placeholder", "error"})
    15.     public static void loadImage(ImageView view, String url, Drawable placeholder, Drawable error) {
    16.         RequestOptions options = new RequestOptions();
    17.         options.placeholder(placeholder);
    18.         options.error(error);
    19.         Glide.with(view).load(url).apply(options).into(view);
    20.     }
    21. }


     
    此时,可在布局文件中使用上面定义的三个属性了,即 imageUrl、placeholder、error,使用方式参考如下:

    1. <layout xmlns:android="http://schemas.android.com/apk/res/android"
    2.     xmlns:app="http://schemas.android.com/apk/res-auto">
    3.     <data> data>
    4.     <LinearLayout
    5.         android:layout_width="match_parent"
    6.         android:layout_height="match_parent"
    7.         android:orientation="vertical"
    8.         android:gravity="center_horizontal">
    9.        
    10.         <ImageView
    11.             android:layout_width="100dp"
    12.             android:layout_height="100dp"
    13.             android:layout_marginTop="10dp"
    14.             app:imageUrl="@{`https://goss.veer.com/creative/vcg/veer/800water/veer-136599950.jpg`}"
    15.             app:placeholder="@{@drawable/icon}"
    16.             app:error="@{@drawable/error}"/>
    17.     LinearLayout>
    18. layout>

     
    此时,三个属性全部使用才能 BindingAdapter 才能正常工作,如果使用了其中的一些属性则不能正常编译通过,那么如何在自定义多个属性而正常使用其中的部分属性呢,@BindingAdapter 注解还有一个参数 requireAll ,requireAll 默认为 true,表示必须使用全部属性,将其设置为 false 就可以正常使用部分属性了,此时,自定义多个属性时要配置 注解 @BindAdapter 的 requireAll 属性为 false,参考如下:

    1. // requireAll = false
    2. @BindingAdapter(value = {"imageUrl", "placeholder", "error"},requireAll = false)
    3. public static void loadImage(ImageView view, String url, Drawable placeholder, Drawable error) {
    4.     RequestOptions options = new RequestOptions();
    5.     options.placeholder(placeholder);
    6.     options.error(error);
    7.     Glide.with(view).load(url).apply(options).into(view);
    8. }
    9.  


    此时,布局文件就可以使用部分属性了,如下面布局文件只使用 imageUrl 和 placeholder 也不会出现编译错误:

    1.  
    2.     android:layout_width="100dp"
    3.     android:layout_height="100dp"
    4.     android:layout_marginTop="10dp"
    5.     app:imageUrl="@{`https://goss.veer.com/creative/vcg/veer/800water/veer-136599950.jpg`}"
    6.     app:placeholder="@{@drawable/icon}"/>


    再来一个例子,

    Android扩大View点击区域

    开发过程中经常会遇到如下这种场景,对于CheckBox而言,整体较小,然后为了用户体验--“好点”,往往需要扩大点击区域。通常的做法就是给CheckBox增加Padding以达到扩大点击区域的目的,但是为了对齐UI,往往需要一通计算跟调整才能“如愿以偿”,可谓哭笑不得。那怎么样可以优雅的解决这个问题呢?

    image.png

    可以配合BindingAdapter实现在xml上的直接处理。BindgingAdapter定义如下:

    1. @BindingAdapter("expandTouchArea")
    2. fun expandTouchArea(view: View, size: String) {
    3. view.postDelayed({
    4. val bounds = Rect()
    5. view.getHitRect(bounds)
    6. var left = 0
    7. var top = 0
    8. var right = 0
    9. var bottom = 0
    10. /*
    11. * size 举例 `2` or `2 4` or `2 4 6 8`
    12. */
    13. val mSize = size.trim()
    14. val ss = mSize.split(" ")
    15. when (ss.size) {
    16. 1 -> {
    17. val sdp = (ss[0].toIntOrNull() ?: 0).idp()
    18. left = sdp
    19. top = sdp
    20. right = sdp
    21. bottom = sdp
    22. }
    23. 2 -> {
    24. val sdp = (ss[0].toIntOrNull() ?: 0).idp()
    25. val sdp1 = (ss[1].toIntOrNull() ?: 0).idp()
    26. left = sdp
    27. top = sdp1
    28. right = sdp
    29. bottom = sdp1
    30. }
    31. 4 -> {
    32. left = (ss[0].toIntOrNull() ?: 0).idp()
    33. top = (ss[1].toIntOrNull() ?: 0).idp()
    34. right = (ss[2].toIntOrNull() ?: 0).idp()
    35. bottom = (ss[3].toIntOrNull() ?: 0).idp()
    36. }
    37. else -> {
    38. return@postDelayed
    39. }
    40. }
    41. bounds.left -= left
    42. bounds.top -= top
    43. bounds.right += right
    44. bounds.bottom += bottom
    45. val mTouchDelegate = TouchDelegate(bounds, view);
    46. val p = view.parent
    47. if (p is ViewGroup) {
    48. p.touchDelegate = mTouchDelegate;
    49. }
    50. }, 100)
    51. }

    其中idp()是dp转px的转换函数(Kotlin扩展),实际使用时请替换

    使用示例:

    1. android:layout_width="14dp"
    2. android:layout_height="14dp"
    3. android:background="@drawable/ic_cb_common"
    4. android:button="@null"
    5. android:checked="false"
    6. app:expandTouchArea="@{`20 10 50 20`}"/>

    参数解析

    1. //表示在View原有范围的基础上在四周增加20dp的区域
    2. app:expandTouchArea="@{`20`}

    1. //表示在View原有范围的基础上左右增加20dp, 上下增加10dp的区域
    2. app:expandTouchArea="@{`20 10`}

    1. //表示在View原有范围的基础上, 左上右下分别增加20dp 10dp 50dp 20dp的区域
    2. 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