Pagination not work for the RecyclerView within NestedScrollView

守給你的承諾、 提交于 2019-11-26 18:58:41
Vishva Dave

Follow this steps :

1. Set nested scrolling enabled false of recycler view.

recyclerView.setNestedScrollingEnabled(false);

2. Add scroll listner to nested scrollview.

 mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
           @Override
           public void onScrollChanged()
           {
                    View view = (View)mScrollView.getChildAt(mScrollView.getChildCount() - 1);

                    int diff = (view.getBottom() - (mScrollView.getHeight() + mScrollView
                                    .getScrollY()));

                    if (diff == 0) {
                       // your pagination code
                    }
           }
  });

if you are using Kotlin your code will be looks like

 scroll?.viewTreeObserver?.addOnScrollChangedListener {
        val view = scroll.getChildAt(scroll.childCount - 1)
        Timber.d("Count==============${scroll.childCount}")

        val diff = view.bottom - (scroll.height + scroll.scrollY)
        Timber.d("diff==============$diff")

        if (diff == 0) {
            //your api call to fetch data
        }
    }

and last but the not the least set RecyclerView scrolling false

 ViewCompat.setNestedScrollingEnabled(recyclerView, false)

I could get the solution setting OnScrollChangeListener in the nestedScrollView.

The field isLoading should be changed everytime you load the items, for example if you are using retrofit. You could set it as true before It start running and as false when you get the response or the failure.

The field isLastPage should be changed everytime you get items and check if this page was the last one.

I'm using kotlin.

private var isLoading = false

private var isLastPage = false

nestedScrollView.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ->

            val nestedScrollView = checkNotNull(v){
                return@setOnScrollChangeListener
            }

            val lastChild = nestedScrollView.getChildAt(nestedScrollView.childCount - 1)

            if (lastChild != null) {

                if ((scrollY >= (lastChild.measuredHeight - nestedScrollView.measuredHeight)) && scrollY > oldScrollY && !isLoading && !isLastPage) {

                    //get more items
                }
            }
        }

And of course you need to set the field isNestedScrollingEnabled as false

myRecyclerView.isNestedScrollingEnabled = false
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!