数据绑定不更新视图文本



我正在使用以下代码实现与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更改CC_2的日期值,视图应以正确格式更新日期值

实际行为 -View不更新日期值。访问 setDate()被调用,但 formatDate()未被调用

何处:

 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>

相关内容

  • 没有找到相关文章