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.
We can use Toast to show sort message in popup as follows:
We need to pass 3 arguement in Toast.makeText as follows:
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:
We can customize Android Toast by creating a xml layout. For this demo, I created a xml layout for toast is given below:
Now, we can use this layout to show message as follows:
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
Step 4: Open res -> layout and create an xml layout named custom_toast.xml. Replace its code with below given code:
Step 5: Open res -> values ->strings.xml and replace its code with below given code:
Step 6: Open res -> values -> colors.xml and replace its code with below given code:
Step 7: Open res -> values -> styles.xml and replace its code with below given code:
Step 8: Open your MainActivity.java and replace it source with below given code as follows:
Step 9: Clean and run the project to see the result.