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!
Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap