android 在RecyclerView底部留一定空间的方法ItemDecoration

android 在[RecyclerView]底部留一定空间的方法ItemDecoration

1.StaggeredGridLayoutManager

 gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
            float offset =100;//这里是你要在最后一个item底部留多少空间
            BottomOffsetDecoration bottomOffsetDecoration = new BottomOffsetDecoration((int) offset);
            recyclerView.addItemDecoration(bottomOffsetDecoration);
            recyclerView.setLayoutManager(gridLayoutManager);
            recyclerView.setAdapter(adapter);
            recyclerView.setItemAnimator(new DefaultItemAnimator());

BottomOffsetDecoration 继承自 RecyclerView.ItemDecoration,在里面判断了当前item是不是最后一个item,如果是就在它的下面加上一个offset,同理,可以在任何已知的item的周围加上offset从而实现特定的效果或需求,

static class BottomOffsetDecoration extends RecyclerView.ItemDecoration {
        private int mBottomOffset;

        public BottomOffsetDecoration(int bottomOffset) {
            mBottomOffset = bottomOffset;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            int dataSize = state.getItemCount();
            int position = parent.getChildAdapterPosition(view);
            StaggeredGridLayoutManager grid = (StaggeredGridLayoutManager) parent.getLayoutManager();
            if ((dataSize - position) <= grid.getSpanCount()) {
                outRect.set(0, 0, 0, mBottomOffset);
            } else {
                outRect.set(0, 0, 0, 0);
            }

        }
    }

2.如果是GridLayout就把StaggeredGridLayoutManager 相应替换就好了,LinearLayoutmanager判断方法有点不一样,其他都是一模一样

 int dataSize = state.getItemCount(); 
 int position = parent.getChildAdapterPosition(view); 
 if(dataSize> 0&& position == dataSize-1){
 outRect.set(0,0,0,mBottomOffset); 
} else {
 outRect.set(0,0,0,0); 
} 
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容