Kotlin DataBinding将静态函数传递到布局xml中 [英] Kotlin DataBinding pass static function into layout xml

查看:633
本文介绍了Kotlin DataBinding将静态函数传递到布局xml中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我可以使用以下方法轻松地将静态函数传递给布局xml:

In Java, i can easily pass static function to layout xml using:

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")}'

但是我用companion在科特林尝试过,但是没有运气.它说

But i tried in Kotlin with companion but no luck. It said

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!

更新 在@Max Aves帮助下.我修复了我的代码,下面的代码可以工作.也许会帮助某人.

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
        }

您可以在xml中使用它

And you can use this in xml

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

推荐答案

您是否尝试添加@JvmStatic注释?应该有帮助!

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

来自官方来源:

指定需要从中生成其他静态方法 该元素是否为函数.如果此元素是属性, 应当生成其他静态的getter/setter方法.

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 DataBinding将静态函数传递到布局xml中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆