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();
}

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!