2

I have a RecyclerView displaying items horizontally and I want to add spacing between each items(but not at the start or end). I found this and also looked at the example from the official docs and even though I have declared the variable using var I get the following error:

enter image description here

I have configured my recycler view as follows:

myRecyclerView.apply {
  layoutManager = myLayoutManager
  adapter = myAdapter(data)
  addItemDecoration(divider)
}

It compiles and runs when I remove the line where I set my custom drawable. Why am I getting this error and how do you set a custom drawable?

Rubek Joshi
  • 562
  • 7
  • 22
  • 1
    Try [calling `setDrawable()`](https://developer.android.com/reference/androidx/recyclerview/widget/DividerItemDecoration#setDrawable(android.graphics.drawable.Drawable)) directly, rather than using the Kotlin property syntax. That Kotlin property syntax should work, as both `getDrawable()` and `setDrawable()` exist. But, either `setDrawable()` will work or its error will (hopefully) give you a better idea of what the real underlying problem is. – CommonsWare Aug 23 '20 at 21:40
  • @CommonsWare can you please explain why the Kotlin property syntax did not work here? – Rubek Joshi Aug 23 '20 at 21:59
  • Off the cuff, I can't. The Kotlin property syntax relies on there being a matching getter and setter, for the same type. It appears that `DividerItemDecoration` has those. Either you are running into some sort of IDE bug, or there is some subtle difference here that I am missing. – CommonsWare Aug 23 '20 at 22:16

3 Answers3

0

As pointed out by CommonsWare, it worked after changing divider.drawable = drawableResource to divider.setDrawable(drawableResource).

Rubek Joshi
  • 562
  • 7
  • 22
0

It happens because in the DividerItemDecoration

public void setDrawable(@NonNull Drawable drawable) 
@Nullable public Drawable getDrawable() 

It means that the setter method accepts a Drawable while the getter return a Drawable?. Since they don't match you have to use the setter directly:

divider.setDrawable(..)
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
0

You can use the extension function below;

fun RecyclerView.setDecoration(@DrawableRes source: Int) {
val itemDecoration = DividerItemDecoration(this.context, DividerItemDecoration.VERTICAL)
ContextCompat.getDrawable(this.context, source)
    ?.let {
        itemDecoration.setDrawable(it)
        this.addItemDecoration(itemDecoration)
    }

}

Usage;

binding.rvFiles.setDecoration(R.drawable.separator_line)
Ahmet B.
  • 1,290
  • 10
  • 20