Android Toast

To display information for a short duration, Android Toast can be used. A message needs to be displayed quickly and to disappear after some time is included in a toast. The java.lang.Object class has a subclass of the android.widget.Toast class. A custom toast like toast displaying an image can also be created.

Toast class:

To show notification for a particular interval of time which disappears after some time, the Toast class is used. The user interaction is not blocked by it.

Constants of Toast class:

The Toast class has only 2 constants:

ConstantUses
public static final int LENGTH_LONGTo display the view for a long duration of time.
public static final int LENGTH_SHORTTo display the view for a short duration of time.

Methods of Toast class:

The methods of Toast class are:

MethodUses
public static Toast makeText(Context context, CharSequence text, int duration)To make a toast that contains text and duration.
public void show()To display a toast.
public void setMargin (float horizontalMargin, float verticalMargin)To change the horizontal and vertical margin difference.

Android Toast Example 1:

Toast.makeText(getApplicationContext(),"Hello World",Toast.LENGTH_SHORT).show();

Android Toast Example 2:

Toast toast=Toast.makeText(getApplicationContext(),"Hello World",Toast.LENGTH_SHORT);  
toast.setMargin(50,50);  
toast.show();

getApplicationContext() method: It returns the instance of Context.

Activity class displaying Toast:

Code to display the toast:

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
  >
 
   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Hello Android!"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent" />
 
</android.support.constraint.ConstraintLayout>

 

File: MainActivity.java

package com.example.app1;
 
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(getApplicationContext(),"Hello World",Toast.LENGTH_LONG).show();
   }
}

 

Output:

Content Protection by DMCA.com
Please Share