Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading