[英]Unable to set Custom Drawable for DividerItemDecoration for RecyclerView
I have a RecyclerView
displaying items horizontally and I want to add spacing between each items(but not at the start or end).我有一个RecyclerView
水平显示项目,我想在每个项目之间添加间距(但不是在开头或结尾)。 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:我发现了这个并且还查看了官方文档中的示例,即使我已经使用 var 声明了变量,但我收到以下错误:
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?为什么会出现此错误以及如何设置自定义可绘制对象?
正如CommonsWare 所指出的,它在将divider.drawable = drawableResource
更改为divider.setDrawable(drawableResource)
。
It happens because in the DividerItemDecoration
发生这种情况是因为在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?
这意味着 setter 方法接受一个Drawable
而 getter 返回一个Drawable?
. . Since they don't match you have to use the setter directly:由于它们不匹配,因此您必须直接使用 setter:
divider.setDrawable(..)
You can use the extension function below;您可以使用下面的分机function;
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.