How to display Toast on Button Click : Android


Lesson for Android Programming Beginners :

Step 1 : Create Button

In your layout.xml file create a button view and set the attribute : android:onClick = "displayToastMsg"

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.toastexample.MainActivity" >
<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:onClick="displayToastMsg"</b>
    android:text="Display Toast Message!" />
</RelativeLayout>

Step 2 : Create Toast Method

Now let's create a method that displays a Toast message when the button is being clicked. Let the method takes in one parameter i.e. the Message to be displayed as String.

public void toastMsg(String msg) {
    Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
    toast.show();
}

Step 3 : Create Button Click Listener Method

Now let's implement Button click Listener that will be called when the button is clicked. We call the toastMsg() function to display the Toast Message.

public void displayToastMsg(View v) {
    toastMsg("Hello how are you today!!");
}

Step 4 : Run the App :

Display Toast Message on Button Click.png
Display Toast Message on Button Click.png

✋️ Now every time the button will be clicked this toast message will be displayed.