在片段中使用 SwipeRefreshLayout 滑动刷新数据?

Swipe to refresh data using SwipeRefreshLayout in fragment?

我希望我的布局在应用程序启动时刷新,数据应该显示在用户滑动时,如果服务器上有新数据可用,数据应该更新并显示新数据。

实际问题是应用程序启动时没有加载数据。相反,它仅在滑动时发生。我怎样才能实现在打开应用程序时先加载数据,然后在滑动时更新数据?

public class FirstFragment extends Fragment {
    FragmentFirstBinding binding;
    APIInterfaces interfaces;
    ArrayList<VideoModels> list = new ArrayList<>();
    @Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentFirstBinding.inflate(inflater, container, false);
        MyAdapter adapter = new MyAdapter(list,getContext());
        binding.myRecyclerView.setAdapter(adapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),2);
        binding.myRecyclerView.setLayoutManager(gridLayoutManager);
        interfaces = RetrofitInstance.getRetrofit().create(APIInterfaces.class);
        binding.swipeToRefresh.setRefreshing(true);
        binding.swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                interfaces.getPosts().enqueue(new Callback<List<VideoModels>>() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onResponse(@NonNull Call<List<VideoModels>> call, @NonNull Response<List<VideoModels>> response) {
                        list.clear();
                        if (response.isSuccessful()) {
                            assert response.body() != null;
                            list.addAll(response.body());
                            adapter.notifyDataSetChanged();
                            binding.swipeToRefresh.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<List<VideoModels>> call, @NonNull Throwable t) {
                        Toast.makeText(getContext(), "Check you Internet", Toast.LENGTH_SHORT).show();
                        binding.swipeToRefresh.setRefreshing(false);
                    }
                });
            }
        });
        binding.swipeToRefresh.setRefreshing(false);

        return binding.getRoot();
    }
}

EDIT-1:添加了完整代码。

你的回答对我有帮助。

如果你打电话 binding.swipeLayout.isRefreshing = true
在 SwipeRefreshLayout 源代码中,mNotify 布尔值是 false 所以无法在 setOnRefreshListener

中执行任何操作
public void onAnimationEnd(Animation animation) {
        if (mRefreshing) {
            // Make sure the progress view is fully visible
            mProgress.setAlpha(MAX_ALPHA);
            mProgress.start();
            if (mNotify) {
                if (mListener != null) {
                    mListener.onRefresh();
                }
            }
            mCurrentTargetOffsetTop = mCircleView.getTop();
        } else {
            reset();
        }
    }

这就是 setOnRefreshListener 不调用的原因 如果你想手动调用它,通过 reflect set mNotify boolean value is true

这样做
val swipeClass = SwipeRefreshLayout::class.java
val method = swipeClass.getDeclaredMethod("setRefreshing", Boolean::class.java, Boolean::class.java)
method.isAccessible = true
method.invoke(binding.swipeLayout, true, true)

需要在onResume()状态下调用此方法

  public void getData() {
            interfaces.getPosts().enqueue(new Callback<List<VideoModels>>() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void onResponse(@NonNull Call<List<VideoModels>> call, @NonNull Response<List<VideoModels>> response) {
                    list.clear();
                    if (response.isSuccessful()) {
                        assert response.body() != null;
                        list.addAll(response.body());
                        adapter.notifyDataSetChanged();
                        binding.swipeToRefresh.setRefreshing(false);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<List<VideoModels>> call, @NonNull Throwable t) {
                    Toast.makeText(getContext(), "Check you Internet", Toast.LENGTH_SHORT).show();
                    binding.swipeToRefresh.setRefreshing(false);
                }
            });
        }

经过 1 天的寻找解决方案。终于,我找到了我的解决方案。

要使用 SwipeRefreshLayoutFragment 工作并希望刷新您的数据 Onswipe。使用以下代码并根据您的要求进行修改。

这是一个fragment

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentFirstBinding.inflate(inflater, container, false);
        // swiping on starting of an app.
        binding.swipeToRefresh.setRefreshing(true);
        getData();
        binding.swipeToRefresh.setRefreshing(false);

        // when user swipe
        binding.swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onRefresh() {
                getData();
            }
        });
        return binding.getRoot();
    }
    public void getData(){
        // you have to put all of your onCreate code here to work properly. most of time it throws an error. So, make sure you added code properly.
        ArrayList<VideoModels> list = new ArrayList<>();
        MyAdapter adapter = new MyAdapter(list,getContext());
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),2);
        binding.myRecyclerView.setAdapter(adapter);
        binding.myRecyclerView.setLayoutManager(gridLayoutManager);
        binding.swipeToRefresh.setRefreshing(true);
        interfaces = RetrofitInstance.getRetrofit().create(APIInterfaces.class);
        interfaces.getPosts().enqueue(new Callback<List<VideoModels>>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onResponse(@NonNull Call<List<VideoModels>> call, @NonNull Response<List<VideoModels>> response) {
                list.clear();
                if (response.isSuccessful()) {
                    assert response.body() != null;
                    list.addAll(response.body());
                    adapter.notifyDataSetChanged();
                    binding.swipeToRefresh.setRefreshing(false);
                }
            }
            @Override
            public void onFailure(@NonNull Call<List<VideoModels>> call, @NonNull Throwable t) {
                Toast.makeText(getContext(), "Check you Internet", Toast.LENGTH_SHORT).show();
                binding.swipeToRefresh.setRefreshing(false);
            }
        });
    }