简体   繁体   中英

How to detect when RecyclerView is scrolled to most top position

I have RecyclerView above that i have an AppBarLayout whose height is larger than 255 px. When user scrolls RecyclerView, AppBarLayout has an fling issue. To avoid that i decided to expand AppBarLayout manually. My RecyclerView made of GridLayoutManager with span of 3. I used below code to listen RecyclerView top reach

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            int firstVisiblePosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
            if (firstVisiblePosition == 0) {
                appBarLayout.setExpanded(true, true);
            }
        }
    }
});
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            int firstVisibleItem = gridLayoutManager.findFirstCompletelyVisibleItemPosition();

            if(firstVisibleItem == 0){
                // your code
            }
        }
    });

This answer will help you. Yours truly

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {

            super.onScrollStateChanged(recyclerView, newState);
        }

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

            totalItemCount = layoutManager.getItemCount();
            visibleItemCount = layoutManager.getChildCount();
            pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
            if ((visibleItemCount + pastVisiblesItems) >= totalItemCount ) {

                Log.d(TAG, "scroll down");



            }
            else{
                Log.d(TAG, "scroll up");
            }
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM