java 添加滚动侦听器以进行无限加载

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 添加滚动侦听器以进行无限加载相关的知识,希望对你有一定的参考价值。

public class CategoriesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{

    private View view;
    private RecyclerView recyclerView;
    private CategoriesAdapter categoriesAdapter;
    private Context context;
    private SwipeRefreshLayout swipeRefreshLayout;
    LinearLayoutManager mLayoutManager;
    ArrayList<Category> categoryItem;
    private boolean loading = true;
    int pastVisiblesItems, visibleItemCount, totalItemCount;
    private int page = 2;

    public CategoriesFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_categories, container, false);

        initialization();
        initScrollListener();

        return view;
    }

    private void initialization() {

        context = getActivity();
        categoryItem = new ArrayList<>();

        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);

        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary);

        recyclerView = view.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));

        /**
         * Showing Swipe Refresh animation on activity create
         * As animation won't start on onCreate, post runnable is used
         */
        swipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        swipeRefreshLayout.setRefreshing(true);
                                        populateData();
                                    }
                                }
        );
    }

    private void initScrollListener() {

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
        {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                if(dy > 0) //check for scroll down
                {
                    visibleItemCount = mLayoutManager.getChildCount();
                    totalItemCount = mLayoutManager.getItemCount();
                    pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

                    if (loading)
                    {
                        if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
                        {
                            //loading = false;
                            Log.v("...", "Last Item Wow !");
                            loadMoreData(page);
                            page++;
                        }
                    }
                }
            }
        });
    }

    private void populateData() {
        Log.v(TAG, "CategoriesFragment() Populate Data has been called!");
        // showing refresh animation before making http call
        swipeRefreshLayout.setRefreshing(true);
        page = 2;
        loading = true;

        CategoriesInterface apiService = APIClient.getClient().create(CategoriesInterface.class);
        Call<CategoriesResponse> call = apiService.getResults();
        call.enqueue(new Callback<CategoriesResponse>() {

            @Override
            public void onResponse(Call<CategoriesResponse> call, Response<CategoriesResponse> response) {

                if (response.isSuccessful()) {

                    try {

                        Constant.showLoading(context, "Videos are being loaded...");

                        List<CategoriesAPI> categories = response.body().getData();

                        Log.v(TAG, "Videos Size: " + categories.size());

                        categoryItem.clear();
                        for (int i = 0; i < categories.size(); i++) {
                            categoryItem.add(new Category(
                                    categories.get(i).getCat_id(),
                                    categories.get(i).getCat_title())
                            );
                        }

                        categoriesAdapter = new CategoriesAdapter(context, categoryItem);
                        recyclerView.setAdapter(categoriesAdapter);

                        Constant.hideLoading();

                    } catch (Throwable e) {
                        Constant.hideLoading();
                        //Constant.showGeneralWarning(context, "Error (Throwable): " + e.getMessage());
                        Log.d(TAG, "Error (Throwable): " + e.getMessage());
                    }

                    // stopping swipe refresh
                    swipeRefreshLayout.setRefreshing(false);

                } else {

                    Constant.hideLoading();

                    if(response.code() == 401){


                    }

                    Log.d(TAG, "Retrofit Failed: " + response.message());
                }

            }

            @Override
            public void onFailure(Call<CategoriesResponse> call, Throwable t) {

                // stopping swipe refresh
                swipeRefreshLayout.setRefreshing(false);

                Log.d(TAG, "Kapuso Error: " + t.getMessage());
            }

        });


    }

    public void loadMoreData(final int page) {

        Constant.showLoading(context, "Loading videos...");

        CategoriesInterface apiService = APIClient.getClient().create(CategoriesInterface.class);
        Call<CategoriesResponse> call = apiService.loadMore(page);
        call.enqueue(new Callback<CategoriesResponse>() {

            @Override
            public void onResponse(Call<CategoriesResponse> call, Response<CategoriesResponse> response) {

                if (response.isSuccessful()) {

                    try {

                        List<CategoriesAPI> categories = response.body().getData();

                        for (int i = 0; i < categories.size(); i++) {
                            categoryItem.add(new Category(
                                    categories.get(i).getCat_id(),
                                    categories.get(i).getCat_title())
                            );
                        }
                        recyclerView.setAdapter(categoriesAdapter);
                        int curSize = categoriesAdapter.getItemCount();
                        categoriesAdapter.notifyItemRangeChanged(curSize, categoryItem.size() - 1);


                        Toast.makeText(context, "adapter size: " + categoryItem.size(), Toast.LENGTH_SHORT).show();

                        Constant.hideLoading();

                        if(page == 2) loading = false;

                    } catch (Throwable e) {
                        Constant.hideLoading();
                        //Constant.showGeneralWarning(context, "Error (Throwable): " + e.getMessage());
                        Log.d(TAG, "Error (Throwable): " + e.getMessage());
                    }

                    Constant.hideLoading();

                } else {

                    Constant.hideLoading();

                    if(response.code() == 401){


                    }

                    Log.d(TAG, "Retrofit Failed: " + response.message());
                }

            }

            @Override
            public void onFailure(Call<CategoriesResponse> call, Throwable t) {

                Constant.hideLoading();
                Log.d(TAG, "Kapuso Error: " + t.getMessage());
            }

        });
    }


    public void onRefresh() {

        populateData();
        initScrollListener();
    }

以上是关于java 添加滚动侦听器以进行无限加载的主要内容,如果未能解决你的问题,请参考以下文章

防止重复无限滚动ajax加载器

如何实现无限滚动插件以从数据库自动加载更多页面滚动数据?

移动端无限加载教程

无尽的滚动监听器

使用 laravel 和 vue 的无限滚动请求未发送以显示数据

ember.js 无限滚动(延迟加载)