我正在为我的RecyclerView使用自定义ItemDecoration,但我不知道为什么未绘制ItemDecoration中最后一个项目的分隔线。如果我使用默认的ItemDecoration类,它可以正常工作并在所有项目(包括最后一个项目)上绘制分隔线
这不会在最后一项上绘制分隔线。为什么会这样?
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
//int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount-1; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(dividerPadding, top, right, bottom);
mDivider.draw(c);
}
}
_________________________________________________________
使用默认的ItemDecoration类有效:
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
mCommentsRecycler.addItemDecoration(dividerItemDecoration);
我还尝试将childCount - 1
更改为childCount
,但这仍然行不通。
答案 0 :(得分:0)
在您的代码中,您还需要覆盖getItemOffset
方法
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if (parent.getChildAdapterPosition(view) == 0) {
return;
}
outRect.bottom = mDivider.getIntrinsicHeight();
}
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
//int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(dividerPadding, top, right, bottom);
mDivider.draw(c);
}
}