Search code examples
androidbuttonkotlinonclicklistener

One `onClickListener` for many buttons in kotlin?


How to create one onClickListener for many buttons in kotlin, i know there is already a solutin for it in Java but how to do it in kotlin ?


Solution

  • You can implement OnClickListener interface at class level and perform the actions by checking the button's ids in overridden method i.e. onClick(v: View?) as follows

    class MainActivity : AppCompatActivity(), View.OnClickListener {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val button1 = findViewById<Button>(R.id.button1)
            val button2 = findViewById<Button>(R.id.button2)
            button1.setOnClickListener(this)
            button2.setOnClickListener(this)
        }
    
        override fun onClick(v: View?) {
    
            when (v?.getId()) {
                R.id.button1 -> firstFun()
                R.id.button2 -> secondFun()
            }
        }
    
        private fun firstFun() {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }
    
        private fun secondFun() {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }
    }
    

    Cheers :)