【发布时间】:2018-12-21 02:04:22
【问题描述】:
我有以下代码:
override fun onCreate(savedInstanceState: Bundle?) {
...
fab_action.setOnClickListener(actionSetMyLocationEnable) //passing my lambda
}
private val actionSetMyLocationEnable: (View) -> Unit = { it as FloatingActionButton
it.isSelected = !it.isSelected
setMyLocationEnable(it.isSelected) //this call work fine
}
private fun setMyLocationEnable(enable: Boolean) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_REQUEST_ACCESS_FINE_LOCATION)
return //and this return work nice too
}
mMap.isMyLocationEnabled = enable
}
但是,当我按如下方式应用它时:
private val actionSetMyLocationEnable: (View) -> Unit = { it as FloatingActionButton
it.isSelected = !it.isSelected
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_REQUEST_ACCESS_FINE_LOCATION)
return //error 1
}
mMap.isMyLocationEnabled = it.isSelected //error 2
}
我正面临这两个错误:
错误 1.
这里不允许'return'
错误 2。
调用需要权限,可能会被用户拒绝:代码应该 明确检查权限是否可用(使用 checkPermission) 或显式处理潜在的 SecurityException
我知道每个错误的含义,但是
我的问题是:为什么我的代码在 lambda 表达式之外可以工作,而在里面却不能工作?我该如何解决这个问题?
更新
@Rene Ferrari's solution 解决了错误1。非常感谢@Rene Ferrari
【问题讨论】:
标签: android lambda kotlin return