ItemDecoration-不确定为什么未绘制最后的分隔线

时间:2019-12-31 01:49:08

标签: android android-recyclerview

我正在为我的RecyclerView使用自定义ItemDecoration,但我不知道为什么未绘制ItemDecoration中最后一个项目的分隔线。如果我使用默认的ItemDecoration类,它可以正常工作并在所有项目(包括最后一个项目)上绘制分隔线

enter image description here

这不会在最后一项上绘制分隔线。为什么会这样?

@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);

enter image description here

我还尝试将childCount - 1更改为childCount,但这仍然行不通。

1 个答案:

答案 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);
        }
    }