问题描述
如何使用这种谷歌语法在 getview(列表视图的)中引用适配器:
fun getView(position: Int,convertView: View?,parent: ViewGroup): View {
return (convertView ?: layoutInflater.inflate(R.layout.my_layout,parent,false)).apply {
// … bind content from position to convertView …
//personal comment : "this" does not refer to adapter
}
}
确实,在 .apply 之后,我必须调用适配器才能生成 adapter.notifyDataSetChanged()
。
使用“经典语法”,可以通过“this”调用适配器,这在谷歌语法中是不可能的。
“经典语法”
fun getView(position: Int,parent: ViewGroup): View {
....
//"this" (refers to adapter)
return convertView
}
那么是否可以覆盖 getview 函数以在签名中添加变量?否则,我的问题的解决方案是什么?
解决方法
您应该使用 .also { ... }
而不是 .apply { ... }
如果我答对了你的问题,你可以:
编写与适配器相同的 getView(...)
函数,但带有附加参数
在适配器覆盖的 getView()
中调用您的 getView(...)
传递您想要的参数。