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 - https://code2care.org/q/android-studio-button-on-click-example

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(R.id.button);
  4. On the myButton object call the onClickListener method with an anonymous implementation. Example:
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
    
            Button myButton = findViewById(R.id.button2);
    
            myButton.setOnClickListener(new View.OnClickListener() {
                @Override
                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/com.app I/System.out: Button Clicked!
2021-04-23 23:29:30.658 6655-6655/com.app I/System.out: Button Clicked!


Have Questions? Post them here!





      Topics: Pages | 2015 | Tutorials | Questions | Python