android-logo

Toast in Android


Toast in android is used to display a message on screen for a small period of time. Toast fades automatically after a timeout has passed. Toast.LENGTH_SHORT and Toast.LENGTH_LONG are two constants to specify duration of Toast.

To create a Toast in Android, we use the makeText() method to instantiate an android.widget.Toast object. The makeText() method takes three parameters: the application context, the text message, and the duration for the toast. Toast notifications can be displayed using the show() method. In addition, you may also create custom toasts, for example one with a picture.



// Syntax to display Toast
Toast.makeText(context, "message", duration).show();
  1. context - This is our application context.
  2. message - Type a message here to display on screen.
  3. duration - Time of toast to simply on screen.
  4. show() - This method is used to display the toast.


// Example
Toast.makeText(MainActivity.this,"Toast Example message",Toast.LENGTH_LONG).show();

MainActivity.java


package com.androidaura.toast;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

      // Toast.makeText(context, p, duration).show();
         Toast.makeText(MainActivity.this, "Toast is Displayed", Toast.LENGTH_SHORT).show();
    }
}
Output
toast-1

previous-button
next-button

facebook-logo
twitter-logo
instagram-logo

2020 © All rights reserved.