gpt4 book ai didi

android - Kotlin - Preference.setOnPreferenceClickListener

转载 作者:行者123 更新时间:2023-11-29 15:36:25 32 4
gpt4 key购买 nike

我正在尝试在我的 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 语句。

我错过了什么?第二种方法与第一种方法不同吗?我该如何摆脱这个错误?

最佳答案

在 lambda 中,最后一条语句自动成为返回值,除非它的返回类型被推断为 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.

关于android - Kotlin - Preference.setOnPreferenceClickListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48839778/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com