[Android Studio] Button on click example

Android Studio Button On Click Demo
Android Studio Button On Click Demo

If you are new to Android Programming and Android Studio IDE and want to know how to perform a button on click action you are at the right place,

In this example I have created a simple project "My Application" that has a hello world text at the center of the Activity, I have replaced it with a button, the activity_main.xml file looks like this, note that I have added a new attribute android:onClick="buttonClicked" which will be the method in MainActivity.java that will perform the action when this button is clicked!

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

        tools:layout_editor_absoluteY="279dp" />

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {


     * This method will be called when the button
     * with id @+id/button is clicked
     * @param view
    public void buttonClicked(View view) {

        Toast.makeText(this,"Hello, you just clicked the button!",

As you can see I have defined the method public void buttonClicked(View view) that will display a toast message when the button is clicked.

⚡️The other way to implement Button on Click action in using onClickListener - check out examples - https://code2care.org/q/android-studio-button-on-click-listener-example

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 - https://donate.unhcr.org/in/en-in/ukraine-emergency