Unable to set Custom Drawable for DividerItemDecoration for RecyclerView

Viewed 152

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?

2 Answers

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

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(..)
Related