使用自定义转换器的双向数据绑定

问题描述 投票:2回答:1

我想将数据绑定与视图模型一起使用,如here所述>

所以这是摘录:

布局:

    <data class="FragmentEditPersonDataBinding">
    <import type="com.unludo.interview.persons.edit.Converter"/>

    <variable
        name="viewmodel"
        type="com.unludo.interview.persons.edit.PersonEditViewModel" />
   [...]
                 <EditText
                android:id="@+id/editBirthday"
                android:inputType="date"
                android:text="@={Converter.dateToString(viewmodel.birthday)}"

转换器:

object Converter {
    @InverseMethod("stringToDate")
    @JvmStatic
    fun dateToString(
            view: EditText, oldValue: String,
            value: Date
    ): String {
        val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE)

        return sdf.format(value)
    }

    @JvmStatic   
    fun stringToDate(
            view: EditText, oldValue: String,
            value: String
    ): Date {
        val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE)

        return sdf.parse(value)
    }
}

viewmodel:

class PersonEditViewModel {
    var birthday: Date = GregorianCalendar(1993, 5, 19).time
    ...

现在在构建时出现此错误:

e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: 
    Found data binding errors.
****/ data binding error ****msg:cannot find method dateToString(java.util.Date) 
    in class com.unludo.interview.persons.edit.Converter 
[...]
 - 134:78 ****\ data binding error ****

我正在使用最新的数据绑定Alpha,所以我想知道lib中是否可能有bug。

谢谢您的帮助!

---更新

如果我这样编写转换器,则它将编译,但是与文档不符。知道为什么吗?

object Converter {

    @InverseMethod("stringToDate")
    @JvmStatic
    fun dateToString(
            value: Date
    ): String {
        val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE)

        return sdf.format(value)
    }
    @JvmStatic
    fun stringToDate(
            value: String
    ): Date {
        val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE)

        return sdf.parse(value)
    }
}

我想在一个视图模型中使用数据绑定,如此处所述,因此摘录如下:layout:[

android android-databinding android-architecture-components android-viewmodel
1个回答
0
投票

有点旧的线程,但是我也一直在努力进行2向数据绑定,所以对于任何需要解决此问题的人来说,问题是Unlundo使转换器的记录方式,有一个View以及旧的和新的价值。但是,有关此文档的内容不是很清楚。

© www.soinside.com 2019 - 2024. All rights reserved.