使用函数 toString("some string") 进行数据绑定

Data binding with the function toString("some string")

我想显示笔记的创建日期。我正在使用数据绑定,我需要使用 toString 函数来获得格式化的日期字符串,但是 toString 函数将字符串作为参数。这是代码:

<data>
        <import type="com.example.path.myproject.model.Note"/>
        <variable
            name="noteViewModel"
            type="com.example.path.myproject.note.NoteViewModel" />
</data>

        <TextView
                    android:id="@+id/createdDate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@{noteViewModel.note.createDate.toString("dd/mm/yyyy")}"
        />

但是我有一个错误,因为我不能在里面使用双引号。我该如何解决?

将该属性放在单引号中,然后您可以在其中使用双引号。

<TextView
    android:id="@+id/createdDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text='@{noteViewModel.note.createDate.toString("dd/mm/yyyy")}'
    />

您可以在字符串值文件中添加一个字符串,然后将值传递给该字符串。

<TextView
android:id="@+id/createdDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text='@{@string/dateString(noteViewModel.note.createDate("dd/mm/yyyy"))}'/>