• 2
    • Or, if you make the extension function be a binding adapter function, it is supposed to work. I haven't tried it yet, but Yi?it mentioned it in the "fireside chat" session at the 2018 Android Developer Summit. Since extension functions are implemented as static Java methods (for Kotlin/JVM), apparently adding the @BindingAdapter annotation was sufficient for it to "just work".
      • 1
    • as @CommonsWare mentions, if you annotate the method with @BindingAdapter("android:setColorifiedText"), then you can use it in xml as ` android:setColorifiedText="@{some text to be colorified}"` (one note though, if you use custom binding adapters, I'd have prefix app:, so it doesn't clash with android's setters)
    • @CommonsWare I annotated the method with @BindingAdapter and I am getting an error stating: {****/ data binding error ****msg:Cannot find the setter for attribute 'app:setColorifiedText' with parameter type androidx.lifecycle.LiveData on android.widget.TextView.}

Yes, it is possible to access an extension function written for a view in XML.

We have prefix the extension function name with 'set' and annotate it with 'BindingAdapter' annotation., for ex:- if your extension function name is 'colorText' change it to 'setColorText' and access the same in XML with the attribute name 'colorText' from 'app:' namespace. Also, annotate the extension function with @BindingAdapter("colorText")

fun TextView.setColorText(text : String) {
   // logic to something with the text

in XML :

   app:colorText="your String" />

you can also modify the code using the kotlin's setter getter to advantage

In case of java declare the function as static and add an argument to the method which gets reference to the textview you gave the attribute to.

  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions