How Can a Divider Line Be Added in an Android Recyclerview

RecyclerView add divider lines only between some items

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.

How to add item divider for RecyclerView in Kotlin

For Kotlin:

 recycler_view.addItemDecoration(
DividerItemDecoration(
context,
LinearLayoutManager.HORIZONTAL
)
)

If you intialized like this:

private lateint var context:Context

then inside your onCreateView

 override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Intialize context here
context = parent.context()
rootView = container?.inflateView(layoutToInflate) ?: View(context)
onFragmentCreated(rootView)
return rootView
}

If you're using inside an activity then instead use

applicationContext

val decorator = DividerItemDecoration(applicationContext, LinearLayoutManager.VERTICAL)
decorator.setDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.file)!!)
recycler_view.addItemDecoration(decorator)

How to add item divider in RecyclerView for specific items

If I needed a divider between sections, I would try to define a type for section headers in recyclerview adapter class globally:

private static final int TYPE_SMS_MESSAGE = 0;
private static final int TYPE_PHONE_CALL = 1;
private static final int TYPE_SECTION_HEADER = 2;

Then I would return a layout with TextView and a divider line below it.

public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_SMS_MESSAGE:
// return a view as you did before
case TYPE_PHONE_CALL:
// return a view as you did before
case TYPE_SECTION_HEADER:
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.section_header_layout, null);
return new YourRecyclerViewHolder(v);
default:
return null;
}
}

To be able to detect and return this layout, you need detect that it is an instance of SectionHeader.

@Override
public int getItemViewType(int position) {
if (itemList.get(position) instanceof SectionHeader) {
return TYPE_SECTION_HEADER;
}
/* return TYPE_SECTION_HEADER if the data in the list is an instance of
SectionHeader and other corresponding types as well */
}

Hope this would help you to have an idea and make progress on it!
Happy Coding :)

Baki



Related Topics



Leave a reply



Submit