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)

Try this for Kotlin

for default item separator

recyclerview.addItemDecoration(DividerItemDecoration(this@YourActivity, LinearLayoutManager.VERTICAL))

drawable as a item separator

val divider = DividerItemDecoration(this@MainActivity,DividerItemDecoration.VERTICAL)
divider.setDrawable(ContextCompat.getDrawable(this@MainActivity,R.drawable.item_separator)!!)
recyclerview.addItemDecoration(divider)

for Java

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

Tags:

Android

Kotlin