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