aridai.NET
【Android】SwipeRefreshingLayoutのisRefreshingのBindingAdapterを作ってみた【DataBinding】

やったこと

SwipeRefreshingLayoutisRefreshing プロパティを DataBinding でバインドできるようにしてみました。

コード

build.gradleapply plugin 'kotlin-kapt'を設定するのを忘れずに!

import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

@BindingAdapter("extensions:isRefreshing")
fun SwipeRefreshLayout.isRefreshingBindingAdapter(value: Boolean) {
    if (this.isRefreshing != value) this.isRefreshing = value
}

@InverseBindingAdapter(attribute = "extensions:isRefreshing", event = "extensions:isRefreshingAttributeChanged")
fun SwipeRefreshLayout.isRefreshingInverseBindingAdapter(): Boolean = this.isRefreshing

@BindingAdapter("extensions:isRefreshingAttributeChanged", requireAll = false)
fun SwipeRefreshLayout.setOnRefreshListenerBindingAdapter(listener: InverseBindingListener?) {
    if (listener != null) this.setOnRefreshListener { listener.onChange() }
}
class MyViewModel : ViewModel() {
    val isRefreshing = MutableLiveData<Boolean>().also { it.value = false }
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:extensions="http://schemas.android.com/tools">

    <data>
        <variable name="viewModel" type="net.aridai.myapp.MyViewModel"/>
    </data>

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/swipeRefreshLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            extensions:isRefreshing="@={viewModel.isRefreshing}">

        <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</layout>
作成日: 2019/07/03