Home > Blockchain >  How do I extract the call to setOnClickListener?
How do I extract the call to setOnClickListener?

Time:07-21

I have a bunch of button functions that merely toasts the label on the button.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    binding.button1.setOnClickListener {
        Toast.makeText(activity?.applicationContext,binding.button1.getLabel(), Toast.LENGTH_SHORT).show()
    }
    binding.button2.setOnClickListener {
        Toast.makeText(activity?.applicationContext,binding.button2.getLabel(), Toast.LENGTH_SHORT).show()
    }
    binding.button3.setOnClickListener {
        Toast.makeText(activity?.applicationContext,binding.button3.getLabel(), Toast.LENGTH_SHORT).show()
    }
    binding.button4.setOnClickListener {
        Toast.makeText(activity?.applicationContext,binding.button4.getLabel(), Toast.LENGTH_SHORT).show()
    }
}

I would like to replace these with a single val or fun that extracts all of that Toast code so that I can just use something like

fun toastLabel( button : MyButton ) {
    Toast.makeText(activity?.applicationContext,button.getLabel(), Toast.LENGTH_SHORT).show()
}

binding.button1.setOnClickListener( toastLabel( binding.button1 ) )

or

val toastLabel : View.OnClickListener = { button : McButton2 ->
        Toast.makeText(activity?.applicationContext,button.getLabel(), Toast.LENGTH_SHORT).show()
    }

Neither of those even compile. What's the right syntax to do that?

CodePudding user response:

I think it's simpler like this:

fun toastLabel( button : MyButton ) {
  binding.button.setOnClickListener{
    Toast.makeText(activity?.applicationContext,button.getLabel(), Toast.LENGTH_SHORT).show()
  }
}

call function:

toastLabel( binding.button1 )

CodePudding user response:

you can extract it like this

fun toastLabel(label: String):  View.OnClickListener = View.OnClickListener { 
   Toast.makeText(activity?.applicationContext,label, Toast.LENGTH_SHORT).show()
}

// use it like this
binding.button1.apply { 
    setOnClickListener(toastLabel(this.getLabel()))
}
binding.button2.apply { 
    setOnClickListener(toastLabel(this.getLabel()))
}
...
  • Related