Kotlin Android start new Activity

后端 未结 17 2308
不知归路
不知归路 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:26

    I had a similar issue, I started to write my application in Kotlin, after I rewrote one of my activities I wanted to see if there are any issues, the problem was that I was not sure how to send an intent from java file to kotlin file.

    In this case I created a static function in kotlin (companion object), this function is getting a context (from the current activity) and returning the new intent while using the current context ("java" context) while using the kotlin class ("::class.java").

    Here is my code:

     //this code will be in the kotlin activity - SearchActivity
     companion object {
    
        fun newIntent(context: Context): Intent {
            return Intent(context, SearchActivity::class.java)
        }
    }
    
        //this is how you call SearchActivity from MainActivity.java
    Intent searchIntent = SearchActivity.Companion.newIntent(this);
    startActivity(searchIntent);
    

提交回复
热议问题