简体   繁体   中英

Add DividerItemDecoration effect in the begining of RecyclerView

I have a layout that consists of a TextView with a helper text on the top of the layout followed by a RecyclerView with the related items.

I added a DividerItemDecoration to the RecyclerView, but it only divides (I know, that's its name) the elements, but not the helper TextView from the first element of the RecyclerView.

Is there a way to extend the DividerItemDecoration in any way or I need to place an empty View element with background between the TextView and RecyclerView?

There is no way to do what you want using the build-in DividerItemDecoration class.

The divider is drawn in a two-step process. First, getItemOffsets() is used to add space to the bottom of each item in the RecyclerView . Then, onDraw() is used to draw the divider within that space.

A look at the source code:

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
        RecyclerView.State state) {
    ...
    if (mOrientation == VERTICAL) {
        outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
    } else {
        outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
    }
}

Here you can see that space is only added to the bottom (or right, in horizontal mode) of each item. There's no special case for the first item to give it a top offset as well.

private void drawVertical(Canvas canvas, RecyclerView parent) {
    ...
    final int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        final View child = parent.getChildAt(i);
        parent.getDecoratedBoundsWithMargins(child, mBounds);
        final int bottom = mBounds.bottom + Math.round(child.getTranslationY());
        final int top = bottom - mDivider.getIntrinsicHeight();
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(canvas);
    }
    ...
}

Here you can see that the vertical boundaries for the mDivider drawable are computed based on bottom edge of each child view.

You could, of course, create your own implementation of RecyclerView.ItemDecoration , and create a special case for the first item in the list.

Edit : Here's a stripped-down and simplified ItemDecoration that is based on DividerItemDecoration but also draws a divider on top of the first item: https://gist.github.com/zizibaloob/0c6be3e1318257950507e9c614c8aa70

You can use View in your xml to divide recyclerView and TextView as below :

<View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorPrimary" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM