科特林 - Preference.setOnPreferenceClickListener
Kotlin - Preference.setOnPreferenceClickListener
我正在尝试在我的 SettingsFragment 中添加一个 onPreferenceClickListener,如果我这样做的话:
signOutPref.setOnPreferenceClickListener(object: Preference.OnPreferenceClickListener {
override fun onPreferenceClick(preference: Preference?): Boolean {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
return true
}
})
在给出警告的同时完美运行:
Use property access syntax
而如果我这样写:
signOutPref.setOnPreferenceClickListener {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
return true
}
这应该是完全一样的东西,这是最好的方法,我得到了:
The Boolean literal does not conform to the expected type Unit
关于 return true
声明。
我错过了什么?第二种方法与第一种方法不同吗?我该如何摆脱这个错误?
您必须使用 return@setOnPreferenceClickListener true
。
说明
:
In Kotlin, the return@label syntax is used for specifying which
function among several nested ones this statement returns from.
在 lambda 中,最后一条语句自动成为 returned 值,除非它的 return 类型被推断为 Unit
。所以只需删除 return
.
signOutPref.setOnPreferenceClickListener {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
true
}
文档说:
A lambda expression is always surrounded by curly braces, parameter declarations in the full syntactic form go inside curly braces and have optional type annotations, the body goes after an -> sign. If the inferred return type of the lambda is not Unit
, the last (or possibly single) expression inside the lambda body is treated as the return value.
我正在尝试在我的 SettingsFragment 中添加一个 onPreferenceClickListener,如果我这样做的话:
signOutPref.setOnPreferenceClickListener(object: Preference.OnPreferenceClickListener {
override fun onPreferenceClick(preference: Preference?): Boolean {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
return true
}
})
在给出警告的同时完美运行:
Use property access syntax
而如果我这样写:
signOutPref.setOnPreferenceClickListener {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
return true
}
这应该是完全一样的东西,这是最好的方法,我得到了:
The Boolean literal does not conform to the expected type Unit
关于 return true
声明。
我错过了什么?第二种方法与第一种方法不同吗?我该如何摆脱这个错误?
您必须使用 return@setOnPreferenceClickListener true
。
说明
In Kotlin, the return@label syntax is used for specifying which function among several nested ones this statement returns from.
在 lambda 中,最后一条语句自动成为 returned 值,除非它的 return 类型被推断为 Unit
。所以只需删除 return
.
signOutPref.setOnPreferenceClickListener {
val signOutIntent = Intent(activity, SignInActivity::class.java)
startActivity(signOutIntent)
true
}
文档说:
A lambda expression is always surrounded by curly braces, parameter declarations in the full syntactic form go inside curly braces and have optional type annotations, the body goes after an -> sign. If the inferred return type of the lambda is not
Unit
, the last (or possibly single) expression inside the lambda body is treated as the return value.