添加无限滚动到我的RecycleView

时间:2016-05-18 08:36:18

标签: android

我正在尝试向我的RecyclerView添加无限滚动。 我从tmdb获取前20部电影,当我向下滚动时,我希望它们重新加载。

现在我遇到了这些问题:

1.找不到适合getActivity()的方法

2.无法找到符号变量spanCount。

有人能帮助我吗? GIthub回购:https://github.com/adnxy/MyMovieApp

我的代码如下:

 mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    mAdapter = new MoviesAdapter(MainActivity.this);
    mRecyclerView.setAdapter(mAdapter);

    final GridLayoutManager mLayoutManager;
    mLayoutManager = new GridLayoutManager(getActivity(), spanCount);
    mRecyclerView.setLayoutManager(mLayoutManager);

无限滚动:

  

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            visibleItemCount = mRecyclerView.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                }
            }
            if (!loading && (totalItemCount - visibleItemCount)
                    <= (firstVisibleItem + visibleThreshold)) {
                // End has been reached

                Log.i("Yaeye!", "end called");

                // Do something

                loading = true;
            }
        }
    });

1 个答案:

答案 0 :(得分:1)

创建三个变量

int pastVisiblesItems, visibleItemCount, totalItemCount;

然后像这样创建LayoutManager

mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);

在最后一次把Listner像这样

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


                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                        Log.w("RecyclerviewListner","Last Item Detected");
                    }

            }
        }
    });