Toolbar in AppBarLayout is scrollable although RecyclerView has not enough content to scroll

前端 未结 9 765
挽巷
挽巷 2020-12-12 15:34

Is it really intended that the Toolbar in a AppBarLayout is scrollable although the main container with the "appbar_scrolling_view_behavior" has not enough content

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 16:05

    Thanks, I created a custom class of RecyclerView but the key is still using setNestedScrollingEnabled(). It worked fine on my side.

    public class RecyclerViewCustom extends RecyclerView implements ViewTreeObserver.OnGlobalLayoutListener
    {
        public RecyclerViewCustom(Context context)
        {
            super(context);
        }
    
        public RecyclerViewCustom(Context context, @Nullable AttributeSet attrs)
        {
            super(context, attrs);
        }
    
        public RecyclerViewCustom(Context context, @Nullable AttributeSet attrs, int defStyle)
        {
            super(context, attrs, defStyle);
        }
    
        /**
         *  This supports scrolling when using RecyclerView with AppbarLayout
         *  Basically RecyclerView should not be scrollable when there's no data or the last item is visible
         *
         *  Call this method after Adapter#updateData() get called
         */
        public void addOnGlobalLayoutListener()
        {
            this.getViewTreeObserver().addOnGlobalLayoutListener(this);
        }
    
        @Override
        public void onGlobalLayout()
        {
            // If the last item is visible or there's no data, the RecyclerView should not be scrollable
            RecyclerView.LayoutManager layoutManager = getLayoutManager();
            final RecyclerView.Adapter adapter = getAdapter();
            if (adapter == null || adapter.getItemCount() <= 0 || layoutManager == null)
            {
                setNestedScrollingEnabled(false);
            }
            else
            {
                int lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition();
                boolean isLastItemVisible = lastVisibleItemPosition == adapter.getItemCount() - 1;
                setNestedScrollingEnabled(!isLastItemVisible);
            }
    
            unregisterGlobalLayoutListener();
        }
    
        private void unregisterGlobalLayoutListener()
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            {
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            else
            {
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        }
    }
    

提交回复
热议问题