@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
稍后再补充……