在Java语言中,我可以很容易地传递静电函数来布局xml,使用:

public static String formatUnixTime(long timeInSeconds, String pattern) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.US);
    String value = simpleDateFormat.format(new Date(timeInSeconds * 1000));

    return value;
}

在XML中:

android:text='@{Utils.formatUnixTime(model.start_time, "hh:mm:ss")}'

但我在Kotlin try 了companion次,但没有成功.上面说

error: cannot find symbol
import my.package.name.HistoryItemBindingImpl;
                      ^
  symbol:   class HistoryItemBindingImpl
  location: package my.package.name

This is what i tried in kotlin

class Utils {
    companion object {
        fun formatUnixTime(timeInSeconds : Long, pattern: String) : String {
            val simpleDateFormat = SimpleDateFormat(pattern, Locale.US)
            val value = simpleDateFormat.format(Date(timeInSeconds * 1000))

            return value
        }
    }

和XML格式

android:text='@{Utils.Companion.formatUnixTime(model.start_time, "hh:mm:ss")}'

Really hope someone can help. Thanks!

Update With @Max Aves help. I fixed my code and below code will work. Maybe it will help someone.

class Utils {
    companion object {
        @JvmStatic
        fun formatUnixTime(timeInSeconds : Long, pattern: String) : String {
            val simpleDateFormat = SimpleDateFormat(pattern, Locale.US)
            val value = simpleDateFormat.format(Date(timeInSeconds * 1000))

            return value
        }

And you can use this in xml

android:text='@{Utils.formatUnixTime(model.start_time, "hh:mm:ss")}'

推荐答案

Have you tried adding @JvmStatic annotation? It should help!

从官方的source分开始:

Specifies that an additional static method needs to be generated from this element if it's a function. If this element is a property, additional static getter/setter methods should be generated.

Kotlin相关问答推荐

在Kotlin中组合多个可为空的集合

kotlin - 挂起简单方法调用链时可能存在冗余分支

在协程上下文中重新抛出异常

如何处理基于枚举提前返回的 forEach 循环,Kotlin 中的一条路径除外

如何在 Kotlin 中将with代码转换为完整代码?

测试协程和线程之间的差异,我在kotlin中使用线程时无法得到OOM错误

如何从 kotlin 函数中 Select 正确的枚举值

is return inside function definition 也是 kotlin 中的表达式

Kotlin - 创建指定长度的随机整数的 ArrayList?

使用纯 Kotlin 函数作为 Junit5 方法源

Kotlin 使用迭代索引过滤 lambda 数组

Kotlin 无法找到或加载主类

在构造函数中仅注入某些参数

无法创建类 ViewModel kotlin 的实例

Android Studio 4.0.0 Java 8 库在 D8 和 R8 构建错误中脱糖

Kotlin默认使用哪种排序?

大小写敏感性 Kotlin / ignoreCase

在 Kotlin 中编写一个等于 Int.MIN_VALUE 的十六进制整数文字

带有注释为@RegisterExtension的字段的 JUnit 5 测试在 Kotlin 中不起作用

Android Compose 生产准备好了吗?