swiperefershlayout在android中不起作用

nfg76nw0  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(406)

swiperefershlayout在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

这是我的主要活动:

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);
    });
6pp0gazn

6pp0gazn1#

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

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);
});

要获得更好的方法,您可以调用 setRefreshing 之后 notifyDataSetChanged 然后从下面取下它 getRoomList 如下图所示:

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

swipeRefreshLayout .

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

相关问题