如何在 GridLayout 的 RecyclerView 项目装饰中跳过第一行?

How to Skip First Row in RecyclerView Item Decoration for GridLayout?

我将此 ItemDecoration class 用于 GridLayout -> https://github.com/devunwired/recyclerview-playground/blob/master/app/src/main/java/com/example/android/recyclerplayground/GridDividerDecoration.java

但问题是,我在 GridLayout 中的第一行是一个图像,我将跨度设置为 2。

您可以按照下面的屏幕截图查看我的屏幕:

如何跳过第一行以使 ItemDecoration 不在图像上绘制?

下面是我用来添加 ItemDecoration 的代码:-

mRecyclerView.setHasFixedSize(true);
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        return position == 0 ? 2 : 1;
    }
});
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter.setHighlightsCallbacks(this);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.addItemDecoration(new GridDividerDecoration(getActivity()));

我还修改了 GridDividerDecoration class 中的 drawHorizo​​ntal 方法,使其仅在 imageview 为 null 时绘制,但仍然无法正常工作:-

public void drawHorizontal(Canvas c, RecyclerView parent) {

    final int top = parent.getPaddingTop();
    final int bottom = parent.getHeight() - parent.getPaddingBottom();

    final int childCount = parent.getChildCount();

    for (int i = 0; i < childCount; i++) {
        final View child = parent.getChildAt(i);
        if (child.findViewById(R.id.home_imgHeader) == null) {
            final RecyclerView.LayoutParams params =
                    (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + params.rightMargin + mInsets;
            final int right = left + mDivider.getIntrinsicWidth();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
}

有什么帮助吗?

假设您的项目没有单独的纯色背景(即白色来自 parent),最简单的解决方法是将代码从 onDrawOver() 移动到 onDraw().这将在 child 视图内容下方绘制网格线,并将隐藏在 header 图像下方。

否则,您使用的代码假定网格线始终绘制到 drawHorizontal() 中视图的顶部(注意 top 是一个永远不会改变的值)。您需要修改该函数以说明第一项的底部并开始在那里绘制。类似于:

public void drawHorizontal(Canvas c, RecyclerView parent) {
    final View topView = parent.findViewHolderForAdapterPosition(0);
    int viewBottom = -1;
    if (topView != null) {
        final RecyclerView.LayoutParams params =
            (RecyclerView.LayoutParams) child.getLayoutParams();
        viewBottom = child.getBottom() + params.bottomMargin + mInsets;
    }

    final int top = viewBottom > parent.getPaddingTop() ? viewBottom : parent.getPaddingTop();
    final int bottom = parent.getHeight() - parent.getPaddingBottom();

    … /* Remaining Code */
}