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.

Advertisements
Try Out Code2care Dev Tools:

Advertisements



#Android #Java #Linux #Microsoft #Google #Python #MacOS #Notepad++ #Microsoft Teams #CSS #PHP #SharePoint #Html #Linux #C-Program #Bootstrap #jQuery #Sublime #Android-Studio #Facebook #Eclipse #WhatsApp #News #MySQL #Json #HowTos #JavaScript #FTP #S3


Advertisements


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