带有数据绑定的 AndroidX SwipeRefreshLayout

AndroidX SwipeRefreshLayout with DataBinding

我正在尝试使用 AndroidX 库实现滑动刷新功能:androidx.swiperefreshlayout.widget.SwipeRefreshLayout

我的应用正在使用 Android 数据绑定,因此我想使用可观察字段来控制此小部件的状态。

过去我使用过 AppCompat one - 它已被弃用。

以前,我可以通过以下方式访问字段:

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:refreshing="@{viewModel.isLoading}">
    ...
    // My RecyclerView here
</android.support.v4.widget.SwipeRefreshLayout>

但是,这似乎不再适用 - 使用 AndroidX 等效项。 我错过了什么吗?或者有什么 solution/workaround 可以实现这个目标吗?

我的项目已经完全迁移到 AndroidX,没有错误或依赖冲突。

您可以为此创建自己的 BindingAdapter

https://developer.android.com/topic/libraries/data-binding/binding-adapters

这就是所谓的androidx.swiperefreshlayout.widget.SwipeRefreshLayout ...

// https://mvnrepository.com/artifact/androidx.swiperefreshlayout/swiperefreshlayout
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

例如:

<?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 />

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/swipe_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:refreshing="@{viewModel.isLoading}"
            app:onRefreshListener="@{() -> viewModel.onRefresh()}">
            ...
        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

    </androidx.appcompat.widget.LinearLayoutCompat>

</layout>

然后onRefresh(),可以从数据绑定中得到RecyclerView.Adapter