对于Android开发,我使用的是Kotlin。有多种按钮(buttonA,buttonB)调用同一功能。唯一的区别是使用不同的参数(REQUEST_A,REQUEST_B)调用同一函数。以下代码运行正常:
fun standardizedFunction(requestCode: Int){
....}
buttonA.setOnClickListener { standardizedFunction(REQUEST_A) }
buttonB.setOnClickListener { standardizedFunction(REQUEST_B) }
现在的问题是:有没有办法使它更优雅?喜欢
fun standardizedFunction(Object: Pointer, requestCode: Int){
Object.setOnClickListener{
....
}
}
standardizedFunction(buttonA,REQUEST_A)
standardizedFunction(buttonB,REQUEST_B)
答案 0 :(得分:1)
您可以使用View
的扩展方法来设置监听器,以使其“更精细”:
fun View.standardizedFunction(requestCode: Int) = setOnClickListener {
...
}