Pre-requisites:
- Android App Development Fundamentals for Beginners
- Guide to Install and Set up Android Studio
- Android | Starting with the first app/android project
- Android | Running your first Android app
What is Toast in Android?
A Toast is a feedback message. It takes a very little space for displaying while the overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If the user wants a permanently visible message, a Notification can be used. Another type of Toast is custom Toast, in which images can be used instead of a simple message.
Example: Toast class provides a simple popup message that is displayed on the current activity UI screen (e.g. Main Activity).
Constants of Toast class
Constants | Description |
---|---|
public static final int LENGTH_LONG | displays for a long time |
public static final int LENGTH_SHORT | displays for a short time |
Methods of Toast class
Methods | Description |
---|---|
public static Toast makeText(Context context, CharSequence text, int duration) | makes the toast message consist of text and time duration |
public void show() | displays a toast message |
public void setMargin (float horizontalMargin, float verticalMargin) | changes the horizontal and vertical differences |
How to Create an Android App to Show a Toast Message?
In this example “This a simple toast message” is a Toast message which is displayed by clicking on the ‘CLICK’ button. Every time when you click your toast message appears.
Step-By-Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Working with the XML Files
Open the “activity_main.xml” file and add a Button to show the Toast message in a Constraint Layout. Also, Assign an ID to the button component as shown in the image and the code below. The assigned ID to the button helps to identify and to use files.
android:id="@+id/id_name"
Here the given ID is Button01 This will make the UI of the Application:
Step 3: Working with the MainActivity File
Now, after the UI, this step will create the Backend of the App. For this, Open the “MainActivity” file and instantiate the component (Button) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.
General Syntax:
ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);
The syntax for the used component (Click Button):
Button btn = (Button)findViewById(R.id.Button01);
Step 4: Operations to Display the Toast Message
Add the listener on the Button and this Button will show a toast message.
btn.setOnClickListener(new View.OnClickListener() {});
Now, Create a toast message. The Toast.makeText() method is a pre-defined method that creates a Toast object. Syntax:
public static Toast makeText (Context context, CharSequence text, int duration)
Parameters: This method accepts three parameters:
A. context: A first parameter is a Context object which is obtained by calling getApplicationContext().
Context context = getApplicationContext();
B. text: The second parameter is your text message to be displayed.
CharSequence text=”Your text message here”
C. duration: The last parameter is the time duration for the message.
int duration=Toast.LENGTH_LONG;
Display the created Toast Message using the show() method of the Toast class.
Syntax:
public void show ()
The code to show the Toast message:
Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG).show();
Step 5: Now Run the App
Operate it as follows:
- When the app is opened, it displays a “Click” button.
- Click the Click button.
- Then “This a toast message” will be displayed on the screen as a Toast Message.
Complete the Code to display a simple Toast Message:
XML
<? xml version = "1.0" encoding = "utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > <!-- add button for generating Toast message --> < Button android:id = "@+id/Button01" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentStart = "true" android:layout_marginTop = "209dp" android:onClick = "onClick" android:text = "Click" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toTopOf = "parent" tools:ignore = "OnClick" /> </ androidx.constraintlayout.widget.ConstraintLayout > |
Java
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Defining the object for button Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Bind the components to their respective objects by assigning // their IDs with the help of findViewById() method Button btn = (Button)findViewById(R.id.Button01); btn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Displaying simple Toast message Toast.makeText(getApplicationContext(), "This a toast message" , Toast.LENGTH_LONG).show(); } }); } } |
Kotlin
import android.os.Bundle import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Bind the components to their respective objects by assigning // their IDs with the help of findViewById() method val btn = findViewById<Button>(R.id.Button01) btn.setOnClickListener { // Displaying simple Toast message Toast.makeText(applicationContext, "This a toast message" , Toast.LENGTH_LONG).show() } } } |
Output:
How to Change the position of a Toast Message?
If there is a need to set the position of a Toast message, then setGravity() method can be used.
public void setGravity (int gravity, int xOffset, int yOffset)
Parameters: This method accepts three parameters:
gravity: This sets the position of the Toast message. The following constants can be used to specify the position of a Toast:
1.TOP 2.BOTTOM 3.LEFT 4.RIGHT 5.CENTER 6.CENTER_HORIZONTAL 7.CENTER_VERTICAL
- Every constant specifies the position in the X and Y axis, except the CENTER constant which sets the position centered for both horizontal and vertical directions.
- xOffset: This is the offset value that tells how much to shift the Toast message horizontally on the x-axis.
- yOffset: This is the offset value that tells how much to shift the Toast message vertically on the y-axis.
For example:
- To display the Toast at the center: toast.setGravity(Gravity.CENTER, 0, 0);
- To display the Toast at the top, centered horizontally: toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 0);
- To display the Toast at the top, centered horizontally, but 30 pixels down from the top: toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 30);
- To display the Toast at the bottom, rightmost horizontally: toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
Example: Here, in the below example, the Toast is displayed at the Bottom-Right position.
Syntax:
Toast t = Toast.makeText(getApplicationContext(), "This a positioned toast message", Toast.LENGTH_LONG); t.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0); t.show();
Complete Code:
XML
<? xml version = "1.0" encoding = "utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > <!-- add button for generating Toast message --> < Button android:id = "@+id/Button01" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentStart = "true" android:layout_marginTop = "209dp" android:onClick = "onClick" android:text = "Click" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toTopOf = "parent" tools:ignore = "OnClick" /> </ androidx.constraintlayout.widget.ConstraintLayout > |
Java
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Defining the object for button Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Binding the components to their respective objects by assigning // their IDs with the help of findViewById() method Button btn = (Button)findViewById(R.id.Button01); btn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Displaying posotioned Toast message Toast t = Toast.makeText(getApplicationContext(), "This a positioned toast message" , Toast.LENGTH_LONG); t.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0 , 0 ); t.show(); } }); } } |
Kotlin
import android.os.Bundle import android.view.Gravity import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Binding the components to their respective objects by assigning // their IDs with the help of findViewById() method val btn = findViewById<Button>(R.id.Button01) btn.setOnClickListener { // Displaying positioned Toast message val t = Toast.makeText(applicationContext, "This a positioned toast message" , Toast.LENGTH_LONG) t.setGravity(Gravity.BOTTOM or Gravity.RIGHT, 0 , 0 ) t.show() } } } |