Toast Example
To show information for a short while, the underoridized toast can be used. A toast is displayed in the message that it is displayed quickly and disappears after some time.
The Android.widget.Toast class is the subdivision of the java.lang.Object class.
You can also create custom toasts, for example to see the toast displayed image for the custom toast you can go to the next page.
Toast class
Toast class is used to show notifications for a particular interval. After some time it disappears, it does not block the user interaction.
Constants of Toast class
There are only 2 constants of Toast class which are given below.
Constant | Description |
---|---|
public static final int LENGTH_LONG | displays view for the long duration of time. |
public static final int LENGTH_SHORT | displays view for the short duration of time. |
Methods of Toast class
The widely used methods of Toast class are given below.
Method | Description |
---|---|
public static Toast makeText(Context context, CharSequence text, int duration) | makes the toast containing text and duration. |
public void show() | displays toast. |
public void setMargin (float horizontalMargin, float verticalMargin) | changes the horizontal and vertical margin difference. |
Android Toast Example
Toast.makeText(getApplicationContext(),"Hello fastread",Toast.LENGTH_SHORT).show();
Another code:
Toast toast=Toast.makeText(getApplicationContext(),"Hello fastread",Toast.LENGTH_SHORT);
toast.setMargin(50,50);
toast.show();
Here, getApplicationContext() method returns the instance of Context.
Full code of activity class displaying Toast
Let's see the code to display the toast.
File: MainActivity.java
package com.example.toast;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Displaying Toast with Hello fastread message
Toast.makeText(getApplicationContext(),"Hello fastread",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}