i am trying to set up a second page for my android app but when i try to do it my setOnClickListener is red here is the code part:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val MainActivity2 = findViewById<Button>(R.id.button)
Button.setOnClickListener {
val Intent = Intent(this,MainActivity2::class.java)
startActivity(Intent)
}
Does anyone know why the setOnClickListener is red ? (the Button. is not red)
CodePudding user response:
You have assigned your button into the variable named MainActivity2. You do not currently have a variable named Button I assume. You need to use
MainActivity2.setOnClickListener {code here} instead
Another way for you to do the same thing:
In your xml file for your Button element, you can add an onClicked attribute. Example:
<Button
...
android:onClick="deleteAll"
android:clickable="true"/>
In your kotlin file which uses that xml file for the view:
fun deleteAll(view: View) {
doSomething()
}