Подтвердить что ты не робот

Android: добавьте разделитель между элементами в RecyclerView

Я использую RecyclerView с закругленным углом, чтобы сделать его закругленным углом, который я использовал ниже XML:

view_rounded.xml: -

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#008f8471"/>
    <stroke android:width="2dp" android:color="#ffffff" />
    <corners android:radius="10dp"/>
</shape>

fragment_main.xml: -

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/view_rounded"/>

adapter_main.xml: -

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textTitle"
        style="@style/AppTheme.ListTextView"
        />

</LinearLayout>

style.xml: -

<style name="AppTheme.ListTextView" parent="android:Widget.Material.TextView">
  <item name="android:gravity">left</item>
  <item name="android:layout_width">match_parent</item>
  <item name="android:layout_height">wrap_content</item>
  <item name="android:textAllCaps">false</item>
  <item name="android:padding">10dp</item>
  <item name="android:textAppearance">@android:style/TextAppearance.DeviceDefault.Medium</item>
  <item name="android:textColor">@color/tabsScrollColor</item> 
  <item name="android:textStyle">bold</item> 
</style>

Получение (без разделителя элементов):

enter image description here

Требуется (с разделителем элементов):

enter image description here

4b9b3361

Ответ 1

Я сделал так:

onCreateView() фрагмента:

RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));

SimpleDividerItemDecoration.java

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

    public SimpleDividerItemDecoration(Context context) {
        mDivider = context.getResources().getDrawable(R.drawable.recycler_horizontal_divider);
    }

    @Override
    public void onDrawOver(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 + mDivider.getIntrinsicHeight();

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

recycler_horizontal_divider.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <size
        android:width="1dp"
        android:height="1dp" />

    <solid android:color="#2EC590" />

</shape>

Надеюсь, это поможет вам.

Ответ 2

RecyclerView отличается от ListViews. Вам нужно добавить ItemDecorators для просмотра recycler. Как говорится в документах,

ItemDecoration позволяет приложению добавлять специальный чертеж и смещение макета к определенным представлениям элементов из набора данных адаптера. Это может быть полезно для разделителей чертежей между элементами, выделениями, границами визуальной группировки и т.д.

Взгляните на эту ссылку: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ItemDecoration.html

Ответ 3

RecyclerView не имеет параметров, связанных с делителем, для отображения разделителя. Вместо этого вам нужно расширить класс из ItemDecoration и использовать метод addItemDecoration() для отображения разделителя.

Создайте класс с именем DividerItemDecoration.java и вставьте код ниже.

DividerItemDecoration.java

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

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

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

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

Откройте Activity.java и установите украшение элемента с помощью метода addItemDecoration() перед настройкой адаптера.

recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

// set the adapter
recyclerView.setAdapter(mAdapter);

Ответ 4

Хорошо, что я сделал для этого, я сначала создал макет для моей строки адаптера как

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <View
    android:id="@+id/lineView"
    android:layout_width="match_parent"
    android:layout_height="2px"
    android:background="@android:color/black"/>
    <TextView
        android:id="@+id/textTitle"
        style="@style/AppTheme.ListTextView"
        />

   </LinearLayout>

Затем в моем адаптере я проверил первую строку и изменил ее видимость видимости на невидимую

@Override
public void onBindViewHolder(ChildInfoViewHolder holder, final int position) {
    if(position == 0){
        holder.viewLine.setVisibility(View.INVISIBLE);
    }
//...
}

public static class MyViewHolder extends RecyclerView.ViewHolder{
    protected View viewLine;
    public ChildInfoViewHolder(View view) {
        super(view);
        viewLine = view.findViewById(R.id.viewLine);
        //... 
    }
}

Ответ 5

Чтобы добавить разделители в ваш recyclerview, вам нужно использовать декоратор - https://gist.github.com/alexfu/0f464fc3742f134ccd1e после добавления в проект добавить строку recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));

Ответ 6

попробуйте добавить Divider

mListview.addItemDecoration(new DividerItemDecoration(this.getActivity(), LinearLayout.VERTICAL));

Ответ 7

Установите селектор на фоне элемента списка в макете, если вы используете пользовательский адаптер

Ответ 8

Попробуйте следующее: Очень приятное решение от Michel-F. Portzert

public class ClippedListView extends ListView {

    public ClippedListView(Context context) {
        super(context);
    }

    public ClippedListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
        protected void dispatchDraw(Canvas canvas) {
        float radius = 10.0f;
        Path clipPath = new Path();
        RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.dispatchDraw(canvas);
    }
}

Ответ 9

Попробуйте это от Ссылка Android: ListView с закругленными углами

Во-первых, нам нужны чертежи для фона списков: Для записей в середине списка нам не нужны закругленные углы, поэтому создайте xml в своей выпадающей папке "list_entry_middle.xml" со ​​следующим содержимым:

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item>
  <shape>
        <stroke android:width="1px" android:color="#ffbbbbbb" />
  </shape>
</item>
<item android:bottom="1dp" android:left="1dp" android:right="1dp">
 <shape >
       <solid android:color="#ffffffff" />
 </shape>
</item>
</layer-list>

Для закругленных углов создайте еще один xml, "rounded_corner_top.xml":

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item>
  <shape>
        <stroke android:width="1dp" android:color="#ffbbbbbb" />
        <corners android:topLeftRadius="20dp"
    android:topRightRadius="20dp"
     />
  </shape>
</item>
<item android:top="1dp" android:left="1dp" android:right="1dp" android:bottom="1dp">
 <shape >
       <solid android:color="#ffffffff" />
      <corners android:topLeftRadius="20dp"
    android:topRightRadius="20dp"
     />
 </shape>
 </item>

 </layer-list>

Реализация нижней части совершенно такая же, как и с bottomLeftRadius и bottomRightRadius. (возможно, также создать один со всеми закругленными углами, если в списке только одна запись) Для лучшего удобства использования также предоставляйте рисунки с другими цветами для разных состояний, которые элемент списка может иметь и ссылаться на них в другом xml в папке с возможностью рисования ( "selector_rounded_corner_top.xml" ) следующим образом:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/rounded_corner_top_click"
      android:state_pressed="true" />
    <item android:drawable="@drawable/rounded_corner_top_click"
      android:state_focused="true" />
    <item android:drawable="@drawable/rounded_corner_top" />
</selector>

Теперь сделайте то же самое для других фонов списка. Все, что осталось сейчас, состоит в том, чтобы назначить правильный фон в нашем ListAdapter следующим образом:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //...      
    //skipping the view reuse stuff

   if (position == 0 && entry_list.size() == 1) {
            view.setBackgroundResource(R.drawable.selector_rounded_corner);
        } else if (position == 0) {
            view.setBackgroundResource(R.drawable.selector_rounded_corner_top);
        } else if (position == entry_list.size() - 1) {
            view.setBackgroundResource(R.drawable.selector_rounded_corner_bottom);
        } else {
            view.setBackgroundResource(R.drawable.selector_middle);
        }

       //...
       //skipping the filling of the view
   }

Ответ 10

Измените свой ListView, как показано ниже. Добавьте list_bg в качестве фона вашего списка. Также укажите некоторые дополнения для верхней и нижней части списка, иначе 1-й и последний элемент в списке будет перекрываться с закругленными углами, показывающими прямоугольные углы.

<ListView
    android:id="@+id/listView"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:background="@drawable/list_bg"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:fastScrollEnabled="true"
    android:choiceMode="singleChoice" />

Ответ 11

Используйте этот гибкий xml для просмотра формы кривой и установите фон в свой список или любой макет:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
           <corners android:radius="6dp" />

            <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
        </shape>

Ответ 12

Попробуйте это

custom_rounded_list.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#ff2521"
        android:endColor="#2f5511"
        android:angle="270"/>
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />
</shape>

Ваше расписание:

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mylst"
    android:background="@drawable/custom_rounded_list" />

Ответ 13

вы устанавливаете list_selector для фона textview и listview. Используйте list_selector только для listview, и если вы хотите, чтобы эффект зависания также отображался в текстовом режиме, создайте еще один list_selector_textview, который не включает свойство <corners android:radius="10dp".

Ответ 14

Проблема заключается в том, что вы устанавливаете фон с углами не только в виде списка, но и в элемент. Вы должны сделать отдельные фоны для элемента (с селектором) и один для просмотра списка с углами.

list_bg.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#008f8471"/>
    <stroke android:width="1dip" android:color="#ffffff" />
    <corners android:radius="10dp"/>
    <padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>

Теперь вы можете настроить этот чертеж в качестве фона вашего списка.

<ListView
    android:id="@+id/listView"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:background="@drawable/list_bg.xml"
    android:fastScrollEnabled="true"
    android:choiceMode="singleChoice" />

И для элемента просмотра списка вы можете использовать селектор для функциональности зависания: list_item_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/list_item_selected" android:state_pressed="true"/>
    <item android:drawable="@drawable/list_item_selected" android:state_pressed="false" android:state_selected="true"/>
    <item android:drawable="@android:color/transparent"/>

Где list_item_selected: list_item_selected.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#4d8f8471"/>
    <stroke android:width="1dip" android:color="#ffffff" />
</shape>

И после этого вы можете настроить этот селектор на элемент в вашем xml:

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"        
    android:background="@drawable/list_item_selector" />

Таким образом, ваше представление списка всегда будет иметь одинаковый фон с углами, а фон элементов списка, будет без углов и будет изменен в нажатом или выбранном состоянии.

Ответ 15

Только одна строка...

recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));

Что все

Ответ 16

Эта строка кода работала для меня:

recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL));

Для вертикальной линии передайте второй аргумент как DividerItemDecoration.VERTICAL.