Home>

How in Kotlin can you find out which button was pressed? Something like onClick in java

You write code in java, copy it, paste it into the Kotlin code. Android Studio converts it as needed. Profit

Arty Morris2021-02-23 20:53:49
  • Answer # 1

    Question in English SO

    Method # 1

    button.setOnClickListener {
        //Do some work here
    }
    

    Method # 2

    button.setOnClickListener (object: View.OnClickListener {
        override fun onClick (view: View?) {
            //Do some work here
        }
    })
    

    Method # 3

    button.setOnClickListener (View.OnClickListener {view ->
        //Do some work here
    })
    

    Method # 4

    class MainActivity: AppCompatActivity (), View.OnClickListener {
        lateinit var button: Button
        override fun onCreate (savedInstanceState: Bundle?) {
            super.onCreate (savedInstanceState)
            setContentView (R.layout.activity_main)
            button= findViewById (R.id.button1)
            button.setOnClickListener (this)
        }
        override fun onClick (view: View?) {
            when (view? .id) {
                R.id.button1->
    {
                    //do some work here
                }
            }
        }
    }
    

    Method # 5

    class MainActivity: AppCompatActivity () {
        lateinit var button: Button
        override fun onCreate (savedInstanceState: Bundle?) {
            super.onCreate (savedInstanceState)
            setContentView (R.layout.activity_main)
            button= findViewById (R.id.button1)
            button.setOnClickListener (listener)
        }
        val listener= View.OnClickListener {view ->
            when (view.getId ()) {
                R.id.button1 ->
     {
                    //Do some work here
                }
            }
        }
    }
    

    p.s. the answer is general

  • Answer # 2

    You write the code in java, copy it, paste it into the Kotlin code. Android Studio converts it as needed. Profit