我将这个ItemDecoration类用于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类中的drawHorizontal方法,只有当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);
}
}
}
任何帮助?
答案 0 :(得分:4)
假设您的商品没有单独的背景(即白色来自父母),最简单的解决方法是将代码从onDrawOver()
移至onDraw()
。这将在子视图内容下绘制网格线,并将隐藏在标题图像下。
否则,您使用的代码假定网格线始终绘制在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 */
}