自定义 ItemDecoration class 未在最后一项上绘制分隔线

Custom ItemDecoration class is not drawing divider on last item

我有一个自定义的 ItemDecoration class,它没有为我的最后一个项目绘制最后一个分隔线。

自定义装饰class:

public class DividerTest extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public DividerTest(Context context) {
        mDivider = context.getResources().getDrawable(R.drawable.divider_horizontal);
    }

    @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(left, top, right, bottom);
            mDivider.draw(c);

        }
    }

}

用法:

RecyclerAdapter adapter = new RecyclerAdapter(list, this);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
DividerTest divider = new DividerTest(this);
mRecycler.addItemDecoration(divider);
mRecycler.setAdapter(adapter);

当我使用默认的 DividerItemDecoration class 时,它有效:

RecyclerAdapter adapter = new RecyclerAdapter(list, this);
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        mRecycler.addItemDecoration(dividerItemDecoration);
        mRecycler.setAdapter(adapter);

为什么我的自定义物品装饰 class 没有绘制我的最后一个分隔线?

这对我有用,在你的 ItemDecoration class

上将实现添加到 getItemOffsets
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent, @NonNull RecyclerView.State state) {
    int position = parent.getChildAdapterPosition(view);
    if (parent.getAdapter() != null && position == parent.getAdapter().getItemCount()-1) {
        outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
    } else {
        super.getItemOffsets(outRect, view, parent, state);
    }
}