关于kotlin DataBinding更新ui

时间:2018-08-16 03:32:45

标签: kotlin android-databinding

这是我的代码

class UserBean(name: String, url: String): BaseObservable() {
    var mName: String = name
        @Bindable get() = field
        set(value) {
            field = value
            notifyPropertyChanged(BR.mName)
        }
    var mUrl: String = url
        set(value) {
            field = value
            notifyPropertyChanged(BR.user)
        }
}

和布局

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="user"
            type="org.magicalwater.mgkotlin.rxkotlintest.UserBean" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <EditText
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:text="@{user.mName}"/>
        <EditText
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:text="@{user}" />
    </LinearLayout>
</layout>

和BindingConversion将UserBean覆盖为字符串

@BindingConversion
fun coverUserToString(user: UserBean): String = user.mUrl

当我在Activity onCreate上运行代码时

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    var binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    var userBean = UserBean("nameFor", "urlFor")
    binding.user = userBean

    object : CountDownTimer(2000, 2000) {
        override fun onTick(p0: Long) {}
        override fun onFinish() {
            userBean.mName = "nameForChanged"
        }
    }.start()
    object : CountDownTimer(4000, 4000) {
        override fun onTick(p0: Long) {}
        override fun onFinish() {
            userBean.mUrl = "urlForChanged"
        }
    }.start()
}

第一次计时器更改了mName起作用,
但是第二个计时器更改了mUrl并更新了UserBean。

谢谢您的帮助。

0 个答案:

没有答案