Android Toast


Download Android toast sample

Android Toast is used to show sort message in popup to user. Toast message takes only that amount of space that is required to show message, and during that time activity is visible and user can interact with it.

Toasts automatically disappear after a timeout.

Android Toast usage?


We can use Toast to show sort message in popup as follows:

We need to pass 3 arguement in Toast.makeText as follows:

  1. Context: First arguement that need to pass in Toast.makeText is Context object
  2. String: Message which you want to display in Toast, pass as second arguement of Toast.makeText method
  3. int: third parameter that need to pass in Toast.makeText is duration. It can have values Toast.LENGTH_SHORT or Toast.LENGTH_LONG

How to position Toast?


We can change this position with the setGravity(int, int, int) method of Toast object. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, To position Toast in the top left corner, we can set the gravity like this:

Android Toast customization?


We can customize Android Toast by creating a xml layout. For this demo, I created a xml layout for toast is given below:

custom_toast.xml

Now, we can use this layout to show message as follows:

Android Toast customization demo


Android Toast customization demo

Step 1: Create a new project in Android Studio and name it Android Toast.

Step 2: Open res -> layout -> activity_main.xml and add following code

activity_main.xml

Step 4: Open res -> layout and create an xml layout named custom_toast.xml. Replace its code with below given code:

custom_toast.xml

Step 5: Open res -> values ->strings.xml and replace its code with below given code:

strings.xml

Step 6: Open res -> values -> colors.xml and replace its code with below given code:

colors.xml

Step 7: Open res -> values -> styles.xml and replace its code with below given code:

styles.xml

Step 8: Open your MainActivity.java and replace it source with below given code as follows:

MainActivity.java

Step 9: Clean and run the project to see the result.


Share & Like

Tutorial topics

About ApnaTutorials.com

ApnaTutorials.com is for Java, J2ee, Html5 and android developers. All tutorials are well explained and are easy to understand. We have tested every tutorials on our developement environment before posting it in public domain.