SwipeRefreshLayout 在 Android 中不起作用

SwipeRefershLayout is not working in Android

SwipeRefreshLayout 在 Android 中不起作用。

这是我的 XML 代码:

//other code
.....

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipeRefreshLayout"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/searchCardView">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        tools:listitem="@layout/room_dashboard_sample"/>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
.....
//other codes

这是我的 MainActivity:

        modelList = new ArrayList<>();
    dashboardAdapter = new DashboardAdapter(this, modelList);
    binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
    binding.recyclerView.setAdapter(dashboardAdapter);

    modelList.clear();
    firestore.collection("Rooms").orderBy("timestamp", Query.Direction.DESCENDING).get().addOnSuccessListener(queryDocumentSnapshots -> {
        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
        for (DocumentSnapshot d : list) {
            DashboardModel obj = d.toObject(DashboardModel.class);
            modelList.add(obj);
        }
        dashboardAdapter.notifyDataSetChanged();
    }).addOnFailureListener(e -> Timber.d("onFailure: %s", e.getMessage()));

    //please give attension in this below code!
    binding.swipeRefreshLayout.setOnRefreshListener(() -> {
        dashboardAdapter.notifyDataSetChanged();
        binding.swipeRefreshLayout.setRefreshing(false);
    });

最好创建一个特定的方法来调用数据库。您可以将它们包装在一个方法中。

private void getRoomsList(){
    firestore.collection("Rooms").orderBy("timestamp", Query.Direction.DESCENDING).get().addOnSuccessListener(queryDocumentSnapshots -> {
        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
        for (DocumentSnapshot d : list) {
            DashboardModel obj = d.toObject(DashboardModel.class);
            modelList.add(obj);
        }
        dashboardAdapter.notifyDataSetChanged();
    }).addOnFailureListener(e -> Timber.d("onFailure: %s", e.getMessage()));
}

然后,你只需要在onCreateswipeRefreshLayout中调用它。

binding.swipeRefreshLayout.setOnRefreshListener(() -> {
    getRoomList();
    binding.swipeRefreshLayout.setRefreshing(false);
});

为了更好的方法,您可以在 notifyDataSetChanged 之后调用 setRefreshing 并将其从 getRoomList 下面删除,如下所示:

//another code...
dashboardAdapter.notifyDataSetChanged();
binding.swipeRefreshLayout.setRefreshing(false); //place it here

swipeRefreshLayout.

binding.swipeRefreshLayout.setOnRefreshListener(() -> {
    getRoomList();
});