class MainActivity : AppCompatActivity() {
companion object {
fun makeIntent(pos : Int) {
println("${pos} is here!")
var intent = Intent(this, DetailActivity::class.java)
if (intent != null) {
println("intent is not null in makeIntent function")
} else {
println("intent is null in makeIntent function")
}
}
}
...
}
在执行var intent = Intent(...)
时,它看不到意图。为什么?
Intent
构造函数需要Context
作为参数传递。makeIntent
this
内部是对伴随对象实例的引用。伴随对象没有对包含类的实例的引用。因此,您必须以某种方式通过Context
,例如:
class MainActivity : AppCompatActivity() {
companion object {
fun makeIntent(pos : Int, context:Context):Intent {
println("${pos} is here!")
var intent = Intent(context, DetailActivity::class.java)
return intent
}
}
除了 @meinsol 的出色答案之外,如果您向 makeIntent
函数添加一个接收器,您可以保持代码几乎相同:
class MainActivity : AppCompatActivity() {
companion object {
fun Context.makeIntent(pos : Int) { // <- Notice the Context receiver here
println("${pos} is here!")
var intent = Intent(this, DetailActivity::class.java)
// Do what you want with the intent
}
}
...
}
然后,您可以从上下文中的任何位置调用它(makeIntent(5)
(,或者如果您不在上下文中但有一个可用的上下文,请使用它(context.makeIntent(5)
(