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,
- Create a button in your activity XML file,
- Make sure you add an android:id to it,
- Now in your Java Activity class onCreate method, create the object of the button: Button myButton = findViewById(R.id.button);
- 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!"); } }); }

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!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!