gpt4 book ai didi

android - 将 RecyclerView 与 StaggeredGridLayoutManager 一起使用时如何避免项目之间的双倍空间?

转载 作者:可可西里 更新时间:2023-11-01 19:00:12 25 4
gpt4 key购买 nike

我将 RecyclerView 与 StaggeredGridLayoutManager 结合使用来创建一个包含两列的列表。但是如何在左列和右列之间设置右边距。我已经使用此代码从顶部制作右边距,但如何解决列之间的双倍空间。

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;

public SpacesItemDecoration(int space) {
this.space = space;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;

// Add top margin only for the first or second item to avoid double space between items
// Add top margin only for the first or second item to avoid double space between items
if((parent.getChildCount() > 0 && parent.getChildPosition(view) == 0)
|| (parent.getChildCount() > 1 && parent.getChildPosition(view) == 1))
outRect.top = space;
}

在 Activity 中:

recyclerView.addItemDecoration(new SpacesItemDecoration(20));

我试过使用 view.getX(),它总是返回 0。

谁能帮帮我?非常感谢!

最佳答案

以下代码将处理 StaggeredGridLayoutManager、GridLayoutManager 和 LinearLayoutManager。

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

private int halfSpace;

public SpacesItemDecoration(int space) {
this.halfSpace = space / 2;
}

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

if (parent.getPaddingLeft() != halfSpace) {
parent.setPadding(halfSpace, halfSpace, halfSpace, halfSpace);
parent.setClipToPadding(false);
}

outRect.top = halfSpace;
outRect.bottom = halfSpace;
outRect.left = halfSpace;
outRect.right = halfSpace;
}
}

关于android - 将 RecyclerView 与 StaggeredGridLayoutManager 一起使用时如何避免项目之间的双倍空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28913217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com