android - Kotlin Android 启动新 Activity

我想在 Android 上开始另一个 Activity ,但出现此错误:

Please specify constructor invocation; classifier 'Page2' does not have a companion object

在实例化 Intent 类之后。我应该怎么做才能纠正错误?我的代码:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun buTestUpdateText2 (view: View) {
        val changePage = Intent(this, Page2) 
        // Error: "Please specify constructor invocation; 
        // classifier 'Page2' does not have a companion object"

        startActivity(changePage)
    }

}

最佳答案

启动 Activity在java中我们写了Intent(this, Page2.class) ,基本上你必须定义Context在第一个参数和第二个参数中的目标类。根据Intent源代码中的方法 -

 public Intent(Context packageContext, Class<?> cls)

如您所见,我们必须通过 Class<?>输入第二个参数。

写信 Intent(this, Page2)我们从不指定我们将通过类(class),我们正在尝试通过 class Not Acceptable 类型。

使用 ::class.java这是 .class 的替代品在 Kotlin 。使用以下代码开始您的 Activity

Intent(this, Page2::class.java)

例子-

// start your activity by passing the intent
startActivity(Intent(this, Page2::class.java).apply {
    // you can add values(if any) to pass to the next class or avoid using `.apply`
    putExtra("keyIdentifier", value)
})

https://stackoverflow.com/questions/45518139/

相关文章:

list - Kotlin:如何使用列表强制转换:未经检查的强制转换:kotlin.collecti

intellij-idea - IntelliJ 中的 Kotlin Unresolved refe

unit-testing - 如何在 Kotlin 中管理单元测试资源,例如启动/停止数据库连接或嵌

kotlin - 覆盖 Kotlin 数据类的 getter

kotlin - 我们何时应该在 Kotlin 上使用 run、let、apply、also 和 w

java - Kotlin:等效于 KClass 的 getClass()

generics - 通用扩展类 AND 在 Kotlin 中实现接口(interface)

generics - Kotlin 泛型中 "*"和 "Any"之间的区别

string - Kotlin - 如何正确连接字符串

syntax - Kotlin 中的变量名或扩展运算符之前的 Kotlin 星号运算符