Kotlin Extension Functions Databinding

后端 未结 3 1317
独厮守ぢ
独厮守ぢ 2021-02-06 21:36

Is there any possibility to use extension function with a databinding? XML:


    

        
相关标签:
3条回答
  • 2021-02-06 21:55

    While @skiff2011 is correct, one could also use alias to prevent the Kt postfix.

    For example, a certain extension function is located in ExtensionFunctionsKt can be aliased by ExtensionFunctions

    <import
        alias="ExtensionFunctions"
        type="com.helloworld.app.util.ExtensionFunctionsKt" />
    
    <variable
        name="someData"
        type="com.helloworld.app.model.SomeData" />
    

    The ExtensionFunction alias can now be used to call the extension function. The first argument still needs to be the extended class variable.

    <TextView
        android:id="@+id/city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{ExtensionFunctions.doStuff(someData)}" />
    
    0 讨论(0)
  • 2021-02-06 22:01

    You have to import CityKt firstly into xml

    <import type="my.package.domain.country.model.CityKt" />
    

    int the data section then you can use it like this

    <TextView
      android:id="@+id/city"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@{CityKt.streetName(city)}" />
    

    If you review CityKt you will see that there is static Java method with City as first argument

    0 讨论(0)
  • 2021-02-06 22:09

    If using Utils class you can to this:

     object Utils(){
           fun streetName(): String {}
    }
    
    <import
        type="com.helloworld.app.util.Utils" />
    
    
    
      <TextView
                    android:id="@+id/txt" 
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{Utils.INSTANCE.streetName()}"
                  />
    
    0 讨论(0)
提交回复
热议问题