我有以下代码:
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' is not allowed here
错误2.
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
我知道每个错误的含义,但是
我的问题是:为什么我的代码在 lambda 表达式之外工作而在内部却不起作用?我该如何解决这个问题?
已更新
@Rene Ferrari's solution解决错误 1。非常感谢@Rene Ferrari
最佳答案
基于 mTak 回答我的解决方案如下:
private val actionSetMyLocationEnable: (View) -> Unit = returnHere@{ 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@returnHere //error 1
}
mMap.isMyLocationEnabled = it.isSelected //error 2
}
您基本上可以定义要返回的标签。这个标签当然可以命名为关键字以外的任何名称。在此示例中,我将其命名为 returnHere
关于android - 代码在 lambda 表达式之外工作,但不能在内部工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51312442/