我使用下面的代码将分隔符添加到列表中。但我的问题是,我如何才能把边距添加到这些分隔符上,使其看起来像附加的图像。提前谢谢。

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
    layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);

android - 如何向Android DividerItemDecoration添加 margin 开始-LMLPHP

最佳答案

您需要重写方法getItemOffsets(Rect, View, RecyclerView, RecyclerView.State)
见例子:

DividerItemDecoration dividerItemDecoration = new
    DividerItemDecoration(recyclerView.getContext(),layoutManager().getOrientation()){

    private int startMargin = Utils.fromDpToPx(10f);

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (parent.getChildAdapterPosition(view) == 0){
            outRect.set(0, startMargin, 0, 0);
        }
    }
};
recyclerView.addItemDecoration(dividerItemDecoration);

09-25 21:05