【问题标题】:How to add a divider between each grid of RecyclerView?如何在 RecyclerView 的每个网格之间添加分隔线?
【发布时间】:2015-09-18 14:45:51
【问题描述】:

我需要在 RecyclerView 的每个网格之间添加一个分隔线。

RecyclerView recyclerView= (RecyclerView) profileView.findViewById(R.id.profile_recycler_view);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
Adapter Adapter = new Adapter(getActivity());
recyclerView.setAdapter(profileAdapter);

请帮帮我。

示例:

【问题讨论】:

  • 所以你想要一条黑线作为分隔线?

标签: android android-recyclerview divider


【解决方案1】:

为此,您需要 Decoration
示例如下:

public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
    private int offset;

    public ItemOffsetDecoration(int offset) {
        this.offset = offset;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left = offset;
        outRect.right = offset;
        outRect.bottom = offset;
        if(parent.getChildAdapterPosition(view) == 0) {
            outRect.top = offset;
        }
    }
}

在你的活动/片段中

grid.setLayoutManager(new GridLayoutManager(this, 2));
grid.addItemDecoration(new ItemOffsetDecoration(1));

【讨论】:

  • 请阅读问题..它将为每个项目添加分隔符。我不想要那个。我需要如图所示的分隔线。
  • 好的,我明白了。您不能复制/粘贴此代码,但请注意您可以定义哪个组件将受到装饰的影响。但是,如果我说对了,您想要在两者之间添加黑线吗?如果是这种情况,我会为你写解决方案。
【解决方案2】:

我认为,Jagadesh Seeram 是在谈论项目之间的水平分隔线,但 RecyclerView.ItemDecoration 到处都添加了分隔线。

如果你不使用自动滚动到某个项目,你应该这样写:

public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
private int offset;

public ItemOffsetDecoration(int offset) {
    this.offset = offset;
}

@Override
public void getItemOffsets(Rect outRect, View view,
                           RecyclerView parent, RecyclerView.State state) {
    int bottonIndex;
    if (parent.getAdapter().getItemCount() % 2 == 0){
        bottonIndex = parent.getAdapter().getItemCount() - 2;
    } else {
        bottonIndex = parent.getAdapter().getItemCount() - 1;
    }

    if (parent.getChildAdapterPosition(view) < bottonIndex){
        outRect.bottom = offset;
    } else {
        outRect.bottom = 0;
    }

    if(parent.getChildAdapterPosition(view) > 1 ) {
        outRect.top = offset;
    } else {
        outRect.top = 0;
    }

    if( (parent.getChildAdapterPosition(view) % 2 ) == 0) {
        outRect.right = offset;
        outRect.left = 0;
    } else {
        outRect.right = 0;
        outRect.left = offset;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2015-09-23
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2019-11-15
    • 2017-02-01
    相关资源
    最近更新 更多