我定义了一个自定义对话框类跟随构建器模式。我的代码没问题。但是现在我想重建以便能够在java 8 lambda上使用
CustomDialogList.kt
class CustomDialogList(context: Context,
private var title: Int?,
private var icon: Int?,
private var map: Map<String, Any>,
private var listner: OnItemClickListener) : Dialog(context) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.custom_dialog_list)
txtTitle.text = context.getString(title!!)
txtTitle.setCompoundDrawablesWithIntrinsicBounds(icon!!, 0, 0, 0)
val listString: MutableList<String> = mutableListOf()
val listObject: MutableList<Any> = mutableListOf()
for ((k, v) in map) {
listString.add(k)
listObject.add(v)
}
val adapter = ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, listString)
listView.adapter = adapter
listView.setOnItemClickListener { _, _, i, _ ->
listner.onClickResult(this, listObject[i], listString[i], i)
}
}
interface OnItemClickListener {
fun onClickResult(dialog: CustomDialogList, obj: Any?, text: String, position: Int)
}
class Builder(private var context: Context) {
private var listner: OnItemClickListener? = null
private var title: Int? = null
private var icon: Int? = null
private var map: Map<String, Any> = mapOf()
fun withTitle(title: Int): Builder {
this.title = title
return this
}
fun withIcon(icon: Int): Builder {
this.icon = icon
return this
}
fun withMap(map: Map<String, Any>): Builder {
this.map = map
return this
}
fun setOnItemClick(listner: OnItemClickListener): Builder {
this.listner = listner
return this
}
fun show() = CustomDialogList(context, title, icon, map, listner!!).show()
}
}
定义
后的语法CustomDialogList.Builder(this)
.withTitle(R.string.add)
.withIcon(R.drawable.ic_add)
.withMap(mapOf())
.setOnItemClick(object : CustomDialogList.OnItemClickListener {
override fun onClickResult(dialog: CustomDialogList, obj: Any?, text: String, position: Int) {
// do something
dialog.dismiss()
}
})
.show()
这是一个我想要构建的例子
CustomDialogList.Builder(this)
.withTitle(R.string.add)
.withIcon(R.drawable.ic_add)
.withMap(mapOf())
.setOnItemClick({ dialog, obj, text, position ->
// do something
dialog.dismiss()
})
.show()
这是我第一次发帖提问,希望大家都能原谅我的英语不好。谢谢你,任何人都可以帮助我:)。
答案 0 :(得分:1)
KT-7770:SAM不适用于Kotlin中定义的接口。
换句话说,lambda表达式
{ dialog, obj, text, position -> ... }
可以是Java功能接口或Kotlin功能,但不能是Kotlin功能接口。
如果删除OnItemClickListener
界面并写入
typealias OnItemClickListener = (CustomDialogList, Any?, String, Int) -> Unit
在顶级,或修改类型签名,您的第二个示例将起作用(并且您的第一个示例将失败)。如果您改为使用Java定义接口,则两者都可以。