Kotlin Android start new Activity

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

    another simple way of navigating to another activity is

    Intent(this, CodeActivity::class.java).apply {
                        startActivity(this)
                    }
    
    0 讨论(0)
  • 2020-12-08 00:32

    From activity to activity

    val intent = Intent(this, YourActivity::class.java)
    startActivity(intent)
    

    From fragment to activity

    val intent = Intent(activity, YourActivity::class.java)
    startActivity(intent)
    
    0 讨论(0)
  • 2020-12-08 00:33

    To start a new Activity ,

    startActivity(Intent(this@CurrentClassName,RequiredClassName::class.java)
    

    So change your code to :

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }
    
        fun buTestUpdateText2 (view: View) {
            startActivity(Intent(this@MainActivity,ClassName::class.java))
    
            // Also like this 
    
            val intent = Intent(this@MainActivity,ClassName::class.java)
            startActivity(intent)
        }
    
    0 讨论(0)
  • 2020-12-08 00:34

    Well, I found these 2 ways to be the simplest of all outcomes:

    Way #1:

    accoun_btn.setOnClickListener {
                startActivity(Intent(this@MainActivity, SecondActivity::class.java))
            }
    

    Way#2: (In a generic way)

        accoun_btn.setOnClickListener {
            startActivity<SecondActivity>(this)
        }
    
        private inline fun <reified T> startActivity(context: Context) {
                startActivity(Intent(context, T::class.java))
            }
    

    0 讨论(0)
  • 2020-12-08 00:39

    You have to give the second argument of class type. You can also have it a little bit more tidy like below.

    startActivity(Intent(this, Page2::class.java).apply {
        putExtra("extra_1", value1)
        putExtra("extra_2", value2)
        putExtra("extra_3", value3)
    })
    
    0 讨论(0)
提交回复
热议问题