Android进阶十四:Databinding之@BindingAdapter和Component

@BindingAdapter

  • 作用于方法
  • 它定义了xml的属性赋值的java实现
  • 方法必须为公共静(public static)方法,可以有一到多个参数。

问题

在使用databinding的时候,有时候发现:

  • 属性在类中没有对应的setter,如ImageView的android:src,ImageView中没有setSrc()方法,
  • 属性在类中有setter,但是接收的参数不是自己想要的,如android:background属性,对应的setter是setBackgound(drawable),但是我想传一个int类型的id进去,这时候android:background = “@{imageId}”就不行。
  • 没有对应的属性,但是却要实现相应的功能。

    这时候可以使用@BindingAdapter来定义方法,解决上面的问题。

实现

@BindingAdapter的格式为:
单个参数:

@BindingAdapter({"attribute_name"})  
public static void method(View view,Type type){  
    //TO DO:一些view的操作
    …… 
}  

方法里面的第一个参数为控件本身
attribute_name可以自由定义,不过最好与method名称对应。

多个参数:

@BindingAdapter({"attribute_name1","attribute_name2","attribute_name3",……})  
public static void method(View view,Type type1,Type type2,Type type3,……){  
    //TO DO:一些view的操作
    …… 
}  

或者:

@BindingAdapter(value = {"attribute_name1","attribute_name2","attribute_name3",……},requireAll = false)  
public static void method(View view,Type type1,Type type2,Type type3,……){  
    //TO DO:一些view的操作
    …… 
}  

requireAll 属性为false,表示在XML中,属性可以不用全部赋值,若是true,则attribute_name1~attribute_namen属性都要赋值,如果不设置,默认是true。

新建一个类,然后在里面定义@BindingAdapter方法:

public class MyAdpter{
   @BindingAdapter("src")
    public static void setSrc(ImageView view, int resId) {
        view.setImageResource(resId);
    }
    @BindingAdapter("background")
    public static void setBackground(View view, int id) {
        view.setBackground(view.getResources().getDrawable(id));
    }
}

这样就可以在xml中使用:

<ImageView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:src = "@{imageId}"
 />

<ImageView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:background = "@{imageId}"
 />

再来看多参数的例子:

@BindingAdapter(value ={"imageUrl", "error"},requireAll = false)
public static void loadImage(ImageView view, String url, Drawable error) {
   Picasso.with(view.getContext()).load(url).error(error).into(view);
}
……
<import type="android.graphics.drawable.Drawable"/>
<variable
     name = "url"
     type = "String"/>
 <variable
     name = "drawable"
     type = "Drawable"/>   
……
<ImageView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:imageUrl = "@{url}"
     app:error = "@{drawable}"
 />

Component

先看这里:http://blog.csdn.net/marktheone/article/details/52047667
稍后再补充……

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值