android -------- Data Binding的使用 ( 六) 自定义属性

今天来说说DataBinding在自定义属性的使用

默认的android命名空间下,我们会发现并不是所有的属性都能直接通过data binding进行设置,比如margin,padding,还有自定义View的各种属性。

默认资源使用

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <!--通过自定义的data来赋值,data的类型定位string-->
        <variable
            name="data"
            type="String" />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

            <Button
                android:id="@+id/btn_demo8_add"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@{data}" />

    </LinearLayout>

</layout>

添加值:

 demo8Binding.setData("自定义属性-添加");

属性:

@BindingAdapter("android:paddingLeft")
public static void setPaddingLeft(View view, int padding) {
    view.setPadding(padding,
                    view.getPaddingTop(),
                    view.getPaddingRight(),
                    view.getPaddingBottom());
}

图片自定义属性:

/**
     * 1.加载图片,无需手动调用此方法
     * 2.使用@BindingAdapter注解设置自定义属性的名称,imageUrl就是属性的名称,
     * 当ImageView中使用imageUrl属性时,会自动调用loadImage方法,
     *
     * @param imageView ImageView
     * @param url       图片地址
     */
    @BindingAdapter({"imageUrl"})
    public static void loadImage(ImageView imageView, String url) {
        Glide.with(imageView.getContext()).load(url)
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .into(imageView);
    }

添加属性和数据:

  <!-- 当imageUrl属性存在时,会自动调用ImageHelper的loadImage方法 -->
        <ImageView
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:scaleType="centerCrop"
            app:imageUrl="@{userImg.picUrl}"
            android:paddingLeft="@{15}"
            />

我只是简单的举几个例子,还可以定义其他的属性。

 参考文档:http://blog.zhaiyifan.cn/2016/07/06/android-new-project-from-0-p8/

猜你喜欢

转载自www.cnblogs.com/zhangqie/p/9636754.html