失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > android网格布局间隙 RecyclerView网格布局瀑布流布局设置间距

android网格布局间隙 RecyclerView网格布局瀑布流布局设置间距

时间:2021-11-18 11:09:45

相关推荐

android网格布局间隙 RecyclerView网格布局瀑布流布局设置间距

RecyclerView在网格布局或者瀑布流布局下,如果要设置间距,可以使用ItemDecoration。

下面的代码是设置显示两列数据RecyclerView的情况。

cat.png

@Override

public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {

super.getItemOffsets(outRect, view, parent, state);

//设置上下间距

if (isFirstRaw(parent.getChildAdapterPosition(view))) {

outRect.top = space;

} else {

outRect.bottom = space;

}

//判断左右列,方法1

//设置列间距

if (parent.getChildAdapterPosition(view) % 2 == 0) {

//左列

outRect.right = space / 2;

} else {

//右列

outRect.left = space / 2;

}

//判断左右列,方法2(推荐)

// GridLayoutManager.LayoutParams params = ((GridLayoutManager.LayoutParams) view.getLayoutParams());

// if (params.getSpanIndex() != GridLayoutManager.LayoutParams.INVALID_SPAN_ID) {

// //getSpanIndex方法不管控件高度如何,始终都是左右左右返回index

// if (params.getSpanIndex() % 2 == 0) {

// //左列

// outRect.right = space / 2;

// } else {

// //右列

// outRect.left = space / 2;

// }

// }

}

给了2种方法,第一种方法在网格布局还好,如果在瀑布流布局里,假设图3在左列长图可能过长,所以接下来的图4、图5都可能显示在右列,方法1计算的结果就有问题了。

如果对你有帮助的话,点赞、评论、赞赏都是对我的鼓励,也是支持我写下去的动力,谢谢!

如果觉得《android网格布局间隙 RecyclerView网格布局瀑布流布局设置间距》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。