Ceridoglu
Ceridoglu

Reputation: 75

Kotlin setOnclickListener button is not working

Hello guys i have a problem on click button

    fun mainPage(view: View) {
            val intent = Intent(applicationContext, MainActivity::class.java)
            intent.putExtra("input", userText.text.toString())
            startActivity(intent)
        }

       //second button started in here
         singupButton.setOnClickListener {
            fun crtUser (view: View) {
                val intent = Intent(applicationContext,createUser::class.java)
                startActivity(intent)
            }
        }

but my buttons are not working. Where is my problem?

Upvotes: 5

Views: 16180

Answers (2)

Jorgesys
Jorgesys

Reputation: 126445

You don´t need to define a function declaration (fun), try this:

singupButton.setOnClickListener {view ->
                val intent = Intent(applicationContext,createUser::class.java)
                startActivity(intent)
 }

or just

singupButton.setOnClickListener {
                  val intent = Intent(applicationContext,createUser::class.java)
                  startActivity(intent)
}

This is a basic sample

val myButton = findViewById<Button>(R.id.myButton) as Button
    //set listener
    myButton.setOnClickListener {
        //Action perform when the user clicks on the button.
        Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
    }

Upvotes: 7

ice1000
ice1000

Reputation: 6569

Your problem is, you defined a function in the click listener, you didn't invoke it.

Your original code:

singupButton.setOnClickListener {
     fun crtUser (view: View) {
         val intent = Intent(applicationContext,createUser::class.java)
         startActivity(intent)
     }
}

You should call this function:

singupButton.setOnClickListener { view ->
     fun crtUser (view: View) {
         val intent = Intent(applicationContext,createUser::class.java)
         startActivity(intent)
     }
     crtUser(view)
}

Or don't define this function, just call it:

singupButton.setOnClickListener {
    val intent = Intent(applicationContext,createUser::class.java)
    startActivity(intent)
}

Upvotes: 0

Related Questions