How to know whether a RecyclerView / LinearLayoutManager is scrolled to top or bottom?

后端 未结 11 2088
一向
一向 2020-12-02 06:24

Currently I am using the follow code to check whether SwipeRefreshLayout should be enabled.

private void laySwipeToggle() {
    if (mRecyclerView.getChildCou         


        
11条回答
  •  爱一瞬间的悲伤
    2020-12-02 07:03

    In order to check whether RecyclerView is scrolled to bottom. Use the following code.

    /**
         * Check whether the last item in RecyclerView is being displayed or not
         *
         * @param recyclerView which you would like to check
         * @return true if last position was Visible and false Otherwise
         */
        private boolean isLastItemDisplaying(RecyclerView recyclerView) {
            if (recyclerView.getAdapter().getItemCount() != 0) {
                int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
                if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
                    return true;
            }
            return false;
        }
    

    Some Additional info

    If you want to implement ScrollToBottom in RecyclerView when Edittext is tapped then i recommend you add 1 second delay like this:

     edittext.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP)
                        if (isLastItemDisplaying(recyclerView)) {
    // The scrolling can happen instantly before keyboard even opens up so to handle that we add 1 second delay to scrolling
                            recyclerView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount() - 1);
    
                                }
                            }, 1000);
                        }
                    return false;
                }
            });
    

提交回复
热议问题