问题
I want to add divider lines in my RecyclerView Layout. I already searched some time, but I can only find solutions that utilise RecyclerView.addItemDecoration, which adds the divider between all items. I could create a layout that has a single line and add that to the RecyclerView, but that doesn't seem like an elegant solution to me.
回答1:
You can write a custom RecyclerView.ItemDecoration and draw divider only where you need. And set it to RecyclerView using:
recyclerView.addItemDecoration(new YourItemDecoration());
This is the default DividerItemDecoration source code:
https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/android/support/v7/widget/DividerItemDecoration.java
You can find the divider drawing logic in onDraw method, where it draws divider for all items. You have to change that part based on your needs to draw divider for some items only. getItemOffsets() method adds offset to the item to make space for the divider.
回答2:
DividerItemDecoration myDivider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
myDivider.setDrawable(ContextCompat.getDrawable(context, R.drawable.cutm_dvdr));
yourRecyclerView.addItemDecoration(myDivider);
add cutm_dvdr.xml in drawable folder
<?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="#e20" />
</shape>
回答3:
you can add custom view in recycler view row item layout and set visibility visible or gone set in adapter which row item you want to line you can set.
回答4:
DividerItemDecoration recycleViewDivider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL); recycleViewDivider.setDrawable(ContextCompat.getDrawable(context, R.drawable.recycleview_item_divider));
and add this DividerItemDecoration to you RecycleView RecyclerView.addItemDecoration(recycleViewDivider );
来源:https://stackoverflow.com/questions/45612014/recyclerview-add-divider-lines-only-between-some-items