Kotlin Android start new Activity

后端 未结 17 2283
不知归路
不知归路 2020-12-07 23:33

I want to start another activity on Android but I get this error:

Please specify constructor invocation; classifier \'Page2\' does not have a companio

17条回答
  •  伪装坚强ぢ
    2020-12-08 00:31

    To start an Activity in java we wrote Intent(this, Page2.class), basically you have to define Context in first parameter and destination class in second parameter. According to Intent method in source code -

     public Intent(Context packageContext, Class cls)
    

    As you can see we have to pass Class type in second parameter.

    By writing Intent(this, Page2) we never specify we are going to pass class, we are trying to pass class type which is not acceptable.

    Use ::class.java which is alternative of .class in kotlin. Use below code to start your Activity

    Intent(this, Page2::class.java)
    

    Example -

    val intent = Intent(this, NextActivity::class.java)
    // To pass any data to next activity
    intent.putExtra("keyIdentifier", value)
    // start your next activity
    startActivity(intent)
    

提交回复
热议问题