MVVM增加点击事件绑定

472 阅读1分钟

MainVM

class MainVM: ViewModel() {
    var content = ObservableField<String>()
    var textContent = ObservableField<String>()
}

布局文件

<?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"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="vm"
            type="com.xiangxue.mvx.mvvm.MainVM" />

        <variable
            name="presenter"
            type="com.xiangxue.mvx.mvvm.MainPresenter" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="@{vm.textContent}" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{vm.content}" />

            <EditText
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:text="@={vm.content}" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@{()->presenter.show(vm)}"
                android:text="显示" />


        </LinearLayout>

    </RelativeLayout>
</layout>

添加点击方法

class MainPresenter {
    fun show(mainVM: MainVM){
        mainVM.textContent.set(mainVM.content.get())
    }
}