I want to start another activity on Android but I get this error:
Please specify constructor invocation; classifier \'Page2\' does not have a companio
another simple way of navigating to another activity is
Intent(this, CodeActivity::class.java).apply {
startActivity(this)
}
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)
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)
}
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))
}
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)
})