是否可以使用 XML 布局中的数据绑定访问为 TextView 编写的扩展函数?

Is it possible to access an extension function written for TextView with Databinding in XML layout?

我的 TextView 扩展函数:

fun TextView.setColorifiedText(text : String) {
 // Some logic to change color of text
 setText(text)
}

我的 xml 数据绑定文件:

<layout>
   <data>
      <!--some data-->
   </data>
   <LinearLayout>
      <TextView 
        android:setColorifiedText="some text to be colorified"
      />
   </LinearLayout>
</layout>

是的,可以访问为 XML 中的视图编写的扩展函数。

我们在扩展函数名称前加上 'set' 前缀,并用 'BindingAdapter' 注释对其进行注释,例如:- 如果您的扩展函数名称是 'colorText',请将其更改为 'setColorText',并使用 'app:' 命名空间中的属性名称 'colorText' 在 XML 中访问相同的名称。 另外,使用 @BindingAdapter("colorText")

注释扩展函数
@BindingAdapter("colorText")
fun TextView.setColorText(text : String) {
   // logic to something with the text
}

在 XML 中:

<TextView
   app:colorText="your String" />

您还可以使用 kotlin 的 setter getter 修改代码以发挥优势

在 java 的情况下,将函数声明为静态的,并向方法添加一个参数,该方法获取对您赋予属性的文本视图的引用。