数据绑定不更新视图文本

时间:2019-03-06 16:43:56

标签: android data-binding observable viewmodel

我正在使用下面的代码通过Observable实现数据绑定

可观察

class Model() : BaseObservable() {

    private var  date :Long?=null
    private var  from :String?=null
    private var  to :String?=null


    @Bindable
    fun getFrom(): String? {
        return from
    }

    @Bindable
    fun getDate(): Long? {
        return date
    }

    @Bindable
    fun getTo(): String? {
        return to
    }

    fun setFrom(data: String) {
        from=data
        notifyPropertyChanged(BR.from);
    }

    fun setTo(data: String) {
        to=data
        notifyPropertyChanged(BR.to)
    }


    fun setDate(data: Long) {
        date=data
        notifyPropertyChanged(BR.date)

    }

    fun formatDate():String? {
        return date?.let { it1 -> TBDate(it1).format("dd MMM, yyyy") }

    }

}

xml的视图

<android.support.design.widget.TextInputLayout
    android:id="@+id/tip_date"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/dp_16"
    android:layout_marginRight="@dimen/dp_18"
    app:layout_constraintBottom_toBottomOf="@+id/today"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/today"
    app:layout_constraintTop_toTopOf="@+id/today">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/et_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/date"
        android:text="@{model.formatDate()}"
        android:onClick="@{() -> handler.onClickDate()}"
        android:editable="false"
        android:focusableInTouchMode="false"
        tools:text="12 Feb, Wednesday" />

</android.support.design.widget.TextInputLayout>

Java

override fun onClickXYZ () {
    val calendar = Calendar.getInstance()
    calendar.add(Calendar.DATE, 1)
    viewModel.setDate(calendar.timeInMillis)
}

预期的行为-每当使用Observable更改setDate()的日期值时,视图应以正确的格式更新日期值

实际行为-视图不会更新日期值。可观察到的setDate()被调用但formatDate()未被调用

1 个答案:

答案 0 :(得分:0)

那呢:

 var formattedDate: String? = null


 fun setDate(data: Long) {
     date=data
     formatDate(date)
     notifyPropertyChanged(BR.date)
 }

 fun formatDate(date: Long):String? {
     formattedDate = date.let { it1 -> TBDate(it1).format("dd MMM, yyyy") }
     notifyPropertyChanged(BR.formattedDate)
 }

在xml中,您必须使用:

 <android.support.design.widget.TextInputEditText
        android:id="@+id/et_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/date"
        android:text="@{model.formattedDate}"  <--
        ...
 </android.support.design.widget.TextInputLayout>