Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 414
Ceridoglu Avatar asked Dec 19 '17 23:12

Ceridoglu


People also ask

What is setOnClickListener in Kotlin?

Kotlin setOnClickListener for Button Android Button widget is a UI element generally used to receive user actions as input. You can click on a Button, long press, etc.

Why is my setOnClickListener not working?

You need to put the setOnClickListener in one of the activity callbacks. In your onCreate() method, move the button there and then setOnClickListener() . Save this answer.

How does setOnClickListener work?

How does setOnClickListener do in android? In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.


1 Answers

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()
    }
like image 58
Jorgesys Avatar answered Nov 15 '22 07:11

Jorgesys