3

Есть такая разметка для элемента (т.е. пункта списка для RecyclerView)

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="@dimen/item_all_side_padding">

        <com.makeramen.roundedimageview.RoundedImageView
            android:id="@+id/iconView"
            android:layout_width="@dimen/item_icon_size"
            android:layout_height="@dimen/item_icon_size"
            android:layout_marginRight="@dimen/item_icon_margin_right"
            android:adjustViewBounds="false"
            android:background="@drawable/noimg"
            android:scaleType="center"
            app:riv_border_color="@color/cardview_shadow_start_color"
            app:riv_border_width="4dp"
            app:riv_mutate_background="true"
            app:riv_oval="true" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:maxLines="1"
                android:text="@string/txtName" />

            <TextView
                android:id="@+id/txtFamily"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:maxLines="1"
                android:text="@string/txtFamily" />
        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

Мне нужно чтобы элементы в списке были разделены также как на картинке, т.е чтобы после каждого элемента была линия. Как это сделать?

введите сюда описание изображения

2
  • 4
    Простой способ - добавить данный разделитель в xml разметку каждого итема. Правильный способ - через ItemDecoration в RecyclerView. В sdk есть готовый DividerItemDecoration, но он рисует дивайдер на всю ширину. Для вашего случая нужно будет его вручную кастомизировать.
    – eugeneek
    13 окт 2017 в 11:48
  • @eugeneek а что решает это правильный способ или нет?помоему правильеее то что ненавредит производительност
    – elik
    13 окт 2017 в 16:56

2 ответа 2

3

Для этого можно прописать View- ку

 <View
        android:id="@+id/view1"
        android:layout_width="wrap_content"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray" />
4
  • 1
    т.е. эту вьюшку добавить в cardView или в linearlayout куда нужно?
    – Kolhoznik
    13 окт 2017 в 11:45
  • @Kolhoznik Туда куда тебе нужно если нужно под разметкой LAyot добавь туда если после колоды карт добавь туда .Ты хоть его добавь в Preview посматри .
    – elik
    13 окт 2017 в 11:47
  • @Kolhoznik еслм мой ответ поможет палец вврех и ответ за верный
    – elik
    13 окт 2017 в 11:48
  • Да, все хорошо. То что нужно, спасибо.
    – Kolhoznik
    13 окт 2017 в 11:48
2

Я это делаю с помощью класса DividerItemDecoration унаследованного от RecyclerView.ItemDecoration:

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;
    private int mOrientation;

    public DividerItemDecoration(Drawable divider) {
        mDivider = divider;
    }

    @Override
    public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
        if (mOrientation == LinearLayoutManager.HORIZONTAL) {
            drawHorizontalDividers(canvas, parent);
        } else if (mOrientation == LinearLayoutManager.VERTICAL) {
            drawVerticalDividers(canvas, parent);
        }
    }

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

        mOrientation = ((LinearLayoutManager) parent.getLayoutManager()).getOrientation();
        if (mOrientation == LinearLayoutManager.HORIZONTAL) {
            outRect.left = mDivider.getIntrinsicWidth();
        } else if (mOrientation == LinearLayoutManager.VERTICAL) {
            outRect.top = mDivider.getIntrinsicHeight();
        }
    }

    private void drawHorizontalDividers(Canvas canvas, RecyclerView parent) {
        int parentTop = parent.getPaddingTop();
        int parentBottom = parent.getHeight() - parent.getPaddingBottom();

        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 parentLeft = child.getRight() + params.rightMargin;
            int parentRight = parentLeft + mDivider.getIntrinsicWidth();

            mDivider.setBounds(parentLeft, parentTop, parentRight, parentBottom);
            mDivider.draw(canvas);
        }
    }

    private void drawVerticalDividers(Canvas canvas, RecyclerView parent) {
        int parentLeft = parent.getPaddingTop() * 9;
        int parentRight = 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 parentTop = child.getBottom() + params.bottomMargin;
            int parentBottom = parentTop + mDivider.getIntrinsicHeight();

            mDivider.setBounds(parentLeft, parentTop, parentRight, parentBottom);
            mDivider.draw(canvas);
        }
    }
}

Где parent.getPaddingTop() * 9:

parent.getPaddingTop - верхний Padding RecyclerView, в моем случае он равен 10dp А умножаю на 9, так как от левого края округленного ImageView до текста отступ 90dp

И в Activity или где вы инициализируете ваш RecyclerView:

private void initRecyclerView() {
    mChatsRV.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    mChatsRV.addItemDecoration(new DividerItemDecoration(ContextCompat.getDrawable(this, R.drawable.items_divider)));
}

И сама линия(разметка) items_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="1px" />
    <solid android:color="#e2e2e2" />
</shape>

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.