美文网首页
android 在RecyclerView底部留一定空间的方法I

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

作者: 信仰年輕 | 来源:发表于2023-10-26 10:17 被阅读0次

    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); 
    } 
    

    相关文章

      网友评论

          本文标题:android 在RecyclerView底部留一定空间的方法I

          本文链接:https://www.haomeiwen.com/subject/skmyidtx.html