Android Studio Button onClickListener Example

In my previous example I had shown how you can create your own custom method that can be called when a button is clicked in your Android Activity while working in Android Studio -

Now let's see how you can perform the same action by using the onClickListener,

  1. Create a button in your activity XML file,
  2. Make sure you add an android:id to it,
  3. Now in your Java Activity class onCreate method, create the object of the button: Button myButton = findViewById(;
  4. On the myButton object call the onClickListener method with an anonymous implementation. Example:
        protected void onCreate(Bundle savedInstanceState) {
            Button myButton = findViewById(;
            myButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    System.out.println("Button Clicked!");
Android Studio onClickListener Example
Android Studio onClickListener Example
Output on button Clicked:
2021-04-23 23:29:30.182 6655-6655/ I/System.out: Button Clicked!
2021-04-23 23:29:30.658 6655-6655/ I/System.out: Button Clicked!

Have Questions? Post them here!
Try Out Code2care Dev Tools:


Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR -