[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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="133dp"
        android:layout_height="45dp"
         android:onClick="buttonClicked"
        android:text="Button"
        tools:layout_editor_absoluteX="139dp"
        tools:layout_editor_absoluteY="279dp" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
    }


    /**
     * 
     * 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!",
         Toast.LENGTH_SHORT).show();
    }

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