Kotlin:Java Util日期转换为字符串以进行数据绑定 [英] Kotlin: Java Util Date to String for Databindings
问题描述
我想通过数据绑定在视图中使用我的数据类的日期值. 如果我在Date字段上使用toString()方法,它将起作用.但是我想自定义日期值. 因此,我使用Method创建了Utils对象.这是Util对象
I want to use the Date value of my Data class in view via Databinding. If I use the toString() method on the Date field it works. But I want to customize the Date value. So I created the Utils object with Method. This is the Util object
object DateUtils {
fun toSimpleString(date: Date) : String {
val format = SimpleDateFormat("dd/MM/yyy")
return format.format(date)
}
}
但是如果我想像这样在xml中使用此方法
But if I want to use this method in the xml like this
<data>
<import type="de.mjkd.journeylogger.Utils.DateUtils"/>
<variable
name="journey"
type="de.mjkd.journeylogger.data.Journey"/>
</data>
...
android:text="@{DateUtils.toSimpleString(journey.date)}"
我收到错误cannot find method toSimpleString(java.util.Date) in class ...
这是我的数据类:
data class Journey(var title: String, var date: Date?, var destination: String)
此代码有什么问题?
推荐答案
使用kotlin中的保留字 object ,您真正要做的就是声明一个实例. Java中的等效项或多或少类似于:
Using the reserved word object in kotlin, that you really doing is declare a single instance. the equivalent in java is something more or less like:
class DataUtils {
static DataUtils INSTANCE;
public String toSimpleString()...
}
然后在您调用它时执行DateUtils.INSTANCE.toSimpleString()
then when you call it you do a DateUtils.INSTANCE.toSimpleString()
您应该能够在xml中使用DateUtils.INSTANCE.toSimpleString()
You should capable to use DateUtils.INSTANCE.toSimpleString()
in your xml
为了使toSimpleString
可从静态上下文访问,您必须使用@JvmStatic
In order to make toSimpleString
accessible from static context, you have to flag the method with@JvmStatic
object DateUtils {
@JvmStatic
fun toSimpleString(date: Date) : String {
val format = SimpleDateFormat("dd/MM/yyy")
return format.format(date)
}
}
使用扩展功能(文档)
@file:JvmName("DateUtils")//Use this to change your class name in java, by default is <the file name>Kt (DateUtilsKt in your case)
fun Date.toSimpleString() : String {
val format = SimpleDateFormat("dd/MM/yyy")
return format.format(this)
}
然后,您可以像已经做的那样直接在xml中使用它:
Then you can use it directly in xml as you are already doing:
android:text="@{DateUtils.toSimpleString(journey.date)}"
这篇关于Kotlin:Java Util日期转换为字符串以进行数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!