[databinding] Custom Adapter

@BindingAdapter is used to decorate methods.

Some properties require custom binding logic, a static method decorated with @BindingAdapter can customize the setter operation of the property.

 

Analyze the code first:

companion object {
        @JvmStatic
        @BindingAdapter("bind:test")
        fun customAdapter(view: TextView, text: String) {
            if (text == "123"){
                view.text = "n/a"
            }else{
                view.text = "test"
            }
        }
    }

 

 It must be static, all can only be handled like this in kotlin, don't forget @JvmStatic, or will you report an error.

"bind:test", 'bind' is the namespace, it can be ignored in layout.xml, or it can be written as android:test

The method name is arbitrary, and at least one View is required in the parameter, or an error of missing parameter will be reported.

In this way, the logic can be written in a custom binding adapter

 

Called in layout.xml:

<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:test='@{"123"}'
            />

The output is: "n/a" 

 

refer to:

1.https://www.jianshu.com/p/a05c9735f595 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326020260&siteId=291194637