[SOLVED] Why don't we need to pass an argument to onClick() in android

Issue

Here’s the code

    class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.myButton.setOnClickListener (object: View.OnClickListener {
            override fun onClick(**v: View?**) {
                binding.statusText.text = "Button Clicked"
            }
        })
    }
}

Why does this code work when no argument is passed to onClick. I mean ‘onClick()’ takes a ‘View’ so we must call it like this: ‘onClick(myButton)’.

Solution

You typically never call onClick yourself. The framework does it for you when you physically touch the view. And it will pass the view you actually touched.

You might wonder:

Why does it even pass it?, I know which view I put the listener on

The thing is. You can give the same listener to multiple views. Having this as parameter makes you able to distinguish in the listener which of the views was clicked.

As a side note, this is a more idiomatic way to write it, and does exactly the same as your code

binding.myButton.setOnClickListener {
    binding.statusText.text = "Button Clicked"
}

Writing it like this, will have the view parameter available as it

Answered By – Ivo Beckers

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published.