databinding 实现onClick的页面跳转

阅读更多

有两种方法,简单的一种:

在viewModel中通过传入的view获得context来实现:

 

class MainActivityVM {
。。。
fun onClick(view: View) {
        val context = view.context
        val intent = Intent(context, RecycleViewActivity::class.java)
        context.startActivity(intent)
    }
。。。
}

 xml:

android:onClick="@{(v) -> mainActivityVM.onClick(v)}"

 

 

 

第二种通过回调,这种方法比较复杂:

 首先声明一个DataBindingUtils:

 

class DataBindingUtils {

    companion object {

        var commonMap  = ArrayMap>()

        fun addCallBack(baseActivity: BaseActivity, observable: Observable?, callback: Observable.OnPropertyChangedCallback){
            var callbackArrayMap = commonMap[baseActivity]
            if (callbackArrayMap == null) {
                callbackArrayMap = ArrayMap()
                commonMap[baseActivity] = callbackArrayMap
            }
            observable?.addOnPropertyChangedCallback(callback)
            callbackArrayMap[observable] = callback
        }

        fun removeCallBack(activity: BaseActivity) {
            var callbackArrayMap = commonMap[activity]
            if (callbackArrayMap != null) {
                for (observable in callbackArrayMap.keys) {
                    observable.removeOnPropertyChangedCallback(callbackArrayMap[observable])
                }
            }
        }
    }


}

 然后在MainActivity中调用:

 

 

private fun addCallBack() {

        DataBindingUtils.addCallBack(
                this,
                mainActivityVM?.goToSimple,
                object : Observable.OnPropertyChangedCallback() {
                    override fun onPropertyChanged(p0: Observable?, p1: Int) {
                        goToNext()
                    }

                })
    }

fun goToNext() {
        startActivity()
    }

 接着在viewModel中创建一个回调通知:

 

 

class MainActivityVM {

    var goToSimple = ObservableInt()

    fun goToNext(view: View) { //view这个值看似没有引用,但是不能删去,删去会报错,可能
和onClicked(view)对应
        goToSimple.notifyChange()
    }

。。。

 最后在xml中:

 

android:onClick="@{mainActivityVM::goToNext}"

 

参考:

1.复杂方法:https://www.jianshu.com/p/564bb7f21fcc

2.Best Practice:https://stackoverflow.com/questions/40475334/best-practice-for-android-mvvm-startactivity

你可能感兴趣的:(databinding,onClick)