如何在RecyclerView中的项目之间添加分隔线和空格?

本文翻译自:How to add dividers and spaces between items in RecyclerView?

This is an example of how it could have been done previously in the ListView class, using the divider and dividerHeight parameters: 这是一个示例的示例,该示例可以使用dividerdividerHeight参数在先前的ListView类中完成:

<ListView
    android:id="@+id/activity_home_list_view"
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="8dp"/>

However, I don't see such possibility in the RecyclerView class. 但是,我在RecyclerView类中看不到这种可能性。

<android.support.v7.widget.RecyclerView
    android:id="@+id/activity_home_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"/>

In that case, is it ok to define margins and/or add a custom divider view directly into a list item's layout or is there a better way to achieve my goal? 在那种情况下,可以定义边距和/或将自定义分隔符视图直接添加到列表项的布局中,还是有更好的方法实现我的目标?


#1楼

参考:https://stackoom.com/question/1fITt/如何在RecyclerView中的项目之间添加分隔线和空格


#2楼

Might I direct your attention to this particular file on Github by Alex Fu: https://gist.github.com/alexfu/0f464fc3742f134ccd1e 我是否可以将您的注意力转移到Alex Fu在Github上的特定文件上: https : //gist.github.com/alexfu/0f464fc3742f134ccd1e

It's the DividerItemDecoration.java example file "pulled straight from the support demos".( https://plus.google.com/103498612790395592106/posts/VVEB3m7NkSS ) 这是DividerItemDecoration.java示例文件“直接从支持演示中提取”。( https://plus.google.com/103498612790395592106/posts/VVEB3m7NkSS

I was able to get divider lines nicely after importing this file in my project and add it as an item decoration to the recycler view. 在我的项目中导入此文件并将其作为项装饰添加到回收视图后,我能够很好地获得分隔线。

Here's how my onCreateView look like in my fragment containing the Recyclerview: 这是我的onCreateView在包含Recyclerview的片段中的样子:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_recycler_view, container, false);

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
    mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));

    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    return rootView;
}

I'm sure additional styling can be done, but it's a starting point. 我确定可以进行其他样式设置,但这是一个起点。 :) :)


#3楼

October 2016 Update 2016年10月更新

The version 25.0.0 of Android Support Library introduced DividerItemDecoration class: Android支持库的DividerItemDecoration版本引入了DividerItemDecoration类:

DividerItemDecoration is a RecyclerView.ItemDecoration that can be used as a divider between items of a LinearLayoutManager . DividerItemDecoration是RecyclerView.ItemDecoration,可以用作LinearLayoutManager项目之间的分隔线。 It supports both HORIZONTAL and VERTICAL orientations. 它同时支持HORIZONTALVERTICAL方向。

Usage: 用法:

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

Previous answer 先前的答案

Some answers either use methods that have since become deprecated, or don't give a complete solution, so I tried to do a short, up-to-date wrap-up. 有些答案要么使用自那以后就已弃用的方法,要么不提供完整的解决方案,因此我尝试进行简短的最新总结。


Unlike ListView , the RecyclerView class has no divider-related parameters. ListView不同, RecyclerView类没有与分隔符相关的参数。 Instead, you need to extend ItemDecoration , a RecyclerView 's inner class: 相反,您需要扩展ItemDecoration ,这是RecyclerView的内部类:

An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter's data set. ItemDecoration允许应用程序从适配器的数据集向特定的项目视图添加特殊的图形和布局偏移。 This can be useful for drawing dividers between items, highlights, visual grouping boundaries and more. 这对于在项目,突出显示,可视分组边界等之间绘制分隔线很有用。

All ItemDecorations are drawn in the order they were added, before the item views (in onDraw() ) and after the items (in onDrawOver( Canvas , RecyclerView , RecyclerView.State) . 在项目视图之前(在onDraw() )和项目之后(在onDrawOver( CanvasRecyclerViewRecyclerView.State) ,将按添加顺序绘制所有ItemDecorations

Vertical spacing ItemDecoration Vertical间距ItemDecoration

Extend ItemDecoration , add custom constructor which takes space height as a parameter and override getItemOffsets() method: 扩展ItemDecoration ,添加将空格height作为参数的自定义构造函数,并覆盖getItemOffsets()方法:

public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int verticalSpaceHeight;

    public VerticalSpaceItemDecoration(int verticalSpaceHeight) {
        this.verticalSpaceHeight = verticalSpaceHeight;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
            RecyclerView.State state) {
        outRect.bottom = verticalSpaceHeight;
    }
}

If you don't want to insert space below the last item, add the following condition: 如果不想在最后一项下方插入空格,请添加以下条件:

if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1) {
            outRect.bottom = verticalSpaceHeight;
}

Note: you can also modify outRect.top , outRect.left and outRect.right properties for desired effect. 注意:您也可以修改outRect.topoutRect.leftoutRect.right属性以获得所需的效果。

Divider ItemDecoration 分频器项ItemDecoration

Extend ItemDecoration and override onDraw() method: 扩展ItemDecoration并重写onDraw()方法:

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

    private Drawable divider;

    /**
     * Default divider will be used
     */
    public DividerItemDecoration(Context context) {
        final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
        divider = styledAttributes.getDrawable(0);
        styledAttributes.recycle();
    }

    /**
     * Custom divider will be used
     */
    public DividerItemDecoration(Context context, int resId) {
        divider = ContextCompat.getDrawable(context, resId);
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, 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 + divider.getIntrinsicHeight();

            divider.setBounds(left, top, right, bottom);
            divider.draw(c);
        }
    }
}

You can either call the first constructor that uses the default Android divider attributes, or the second one that uses your own drawable, for example drawable/divider.xml 您可以调用第一个使用默认Android除法器属性的构造函数,也可以调用第二个使用您自己的drawable的构造函数,例如drawable / divider.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <size android:height="1dp" />
    <solid android:color="#ff992900" />
</shape>

Note: if you want the divider to be drawn over your items, override onDrawOver() method instead. 注意:如果要在项目上绘制分隔线onDrawOver()方法。

Usage 用法

To use your new class add VerticalSpaceItemDecoration or DividerSpaceItemDecoration to RecyclerView , for example in your fragment's onCreateView() method: 要使用您的新类,例如,在片段的onCreateView()方法中,将VerticalSpaceItemDecorationDividerSpaceItemDecoration添加到RecyclerView

private static final int VERTICAL_ITEM_SPACE = 48;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_feed, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.fragment_home_recycler_view);
    linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);

    //add ItemDecoration
    recyclerView.addItemDecoration(new VerticalSpaceItemDecoration(VERTICAL_ITEM_SPACE));
    //or
    recyclerView.addItemDecoration(new DividerItemDecoration(getActivity()));
    //or
    recyclerView.addItemDecoration(
            new DividerItemDecoration(getActivity(), R.drawable.divider));

    recyclerView.setAdapter(...);

    return rootView;
}

There's also Lucas Rocha's library which is supposed to simplify the item decoration process. 还有Lucas Rocha的图书馆 ,应该可以简化物品装饰过程。 Haven't tried it though. 还没有尝试过。

Among its features are: 功能包括:

  • A collection of stock item decorations including: 库存物品装饰的集合,包括:
  • Item spacing Horizontal/vertical dividers. 项目间距水平/垂直分隔线。
  • List item 项目清单

#4楼

这实际上并不能解决问题,但是作为一种临时的解决方法,您可以在XML布局中的卡上设置useCompatPadding属性,以使其与Lollipop之前的版本相同。

card_view:cardUseCompatPadding="true"

#5楼

Simple ItemDecoration implementation for equal spaces between all items. 简单的ItemDecoration实现, ItemDecoration实现所有项目之间相等的空间。

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;

    public SpacesItemDecoration(int space) {
        this.space = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left = space;
        outRect.right = space;
        outRect.bottom = space;

        // Add top margin only for the first item to avoid double space between items
        if(parent.getChildAdapterPosition(view) == 0) {
            outRect.top = space;
        }
    }
}

#6楼

Add a margin to your view, it worked for me. 为您的视图增加一个边距,对我有用。

android:layout_marginTop="10dp"

If you just want to add equal spacing and want to do it in XML , just set padding to your RecyclerView and equal amount of layoutMargin to the item you inflate into your RecyclerView , and let the background color determine the spacing color. 如果你只是想刚才设置添加间距相等 ,并希望做它在XML, padding你的RecyclerView和等量layoutMargin你膨胀到你的项目RecyclerView ,并让背景颜色确定的间距颜色。

发布了0 篇原创文章 · 获赞 73 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/w36680130/article/details/105347331