简体   繁体   中英

Calling Kotlin function type from databinding Android

I have a BaseObservable that I use in databinding to display a network state. In this class, I pass in a retry callback that I want to run any time a button is clicked:

class NetworkStateViewModel(val retryCallback: () -> Unit) : BaseObservable() {
    var networkState: NetworkState? = null
        set(value) {
            field = value

            notifyChange()
        }

    val isLoading: Boolean
        @Bindable get() = networkState is NetworkState.Loading

    val isShowingError: Boolean
        @Bindable get() = networkState is NetworkState.Error

    val errorText: String
        @Bindable get() = (networkState as? NetworkState.Error)?.error?.message.orEmpty()
}

However, when I try to reference retryCallback through data binding, it can't compile as it says it's cannot find method retryCallback() in class NetworkStateViewModel .

<Button
    ...
    android:onClick="@{() -> viewModel.retryCallback()}"
    ... />

I have found one work around so far, which I'll post separately as an answer, but I'd like to know if I can call this directly.

Just call invoke method of lambda:

<Button
...
android:onClick="@{() -> viewModel.retryCallback.invoke()}"
... />

One work around to this is to not call the function type directly, but instead write a function that does so:

class NetworkStateViewModel(private val retryCallback: () -> Unit) : BaseObservable() {
    ...

    fun retry() {
        retryCallback()
    }

    ...
}

And in XML:

<Button
    ...
    android:onClick="@{() -> viewModel.retry()}"
    ... />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM