Skip to content
Advertisement

How can I get all the events of the buttons on a screen on android in a single method using the kotlin?

I am developing a Calculator for my android learning using kotlin. To get the numbers select to users, I need to set the code below:

btn1.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "1")
        })
        btn2.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "2")
        })
        btn3.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "3")
        })
        btn4.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "4")
        })
        btn5.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "5")
        })
        btn6.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "6")
        })
        btn7.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "7")
        })
        btn8.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "8")
        })
        btn9.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "9")
        })
        btn0.setOnClickListener({
            var texto = txtDisplay.text.toString()
            txtDisplay.setText(texto + "0")
        })

Is it possible to centrelize the event handling of all buttons in the single class or method?

I would like to a generic solution to reduce the code

Does anyone know a solution?

Advertisement

Answer

this is a standard way to handle click events in kotlin. create Function click listeners in your Class. call this function in onCreate function.

 private fun clickListeners()
 {
 btn1.setOnClickListener(this)

 btn2.setOnClickListener(this)
 }

extend OnclickListner to your Activity/Fragment.

 class A: AppCompatActivity(),View.OnClickListener{
   override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
   // call onclick listener function 
    clickListeners()
 
}
  }

then override onClick function and write your onClick Logic.

   override fun onClick(v: View?) {

    when (v?.id) {

        R.id.btn1-> {
            txtDisplay.text = txtDisplay.text.toString() +"1"
        }
         R.id.btn2-> {
            txtDisplay.text = txtDisplay.text.toString() +"2"
        }
      }
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement