According to real time scenario our application should give proper information to user, so that they can find our application somewhat user friendly. There are so many things that should keep in mind while developing any application for better response like, designing UI, speed of execution, alert types, providing information to the user that what our application is doing now, for example if you are using your alarm application and set the alarm time that you may found that there is small notification appear in our screen for a moment like information that “This alarm set for xx hours and xx minutes from now”. This type of information which is floating on our current screen for a second or two or three is known as Toasts.
[ads_post_responsive]
Android provides us very useful class Toast class resides in android.widget package. Subclass of java.lang.Object class. A toast is a way to display a little message quickly floating on current screen. Thus we can make this type of information popup using android.widget.Toast class. One special attribute of toast is it never gets a focus form the user so we don’t have to handle any event of user interactions. These all are the simple messages, that’s it! To use the toast we can get an object of toast by using static methods from this class itself.
Recommended Read : Android Simple Hello World!
There is very simple static method makeText() which is use to get an object of this class.after getting object we can use show() method to display the toast which will display little short message floating on the UI screen.
There are three ways to get an object of toast.
Constructor
Syntax | Description |
Toast(Context context) | Creates a toast take application context as parameter. |
Methods
Return Type | Method | Description |
static Toast | makeText(Context context, intresourceID, inttoastDuration) | Returns object of Toast class by accepting application context or activity, a String resource to display in message, |
Static Toast | makeText(Context context, CharacterSequence text, int duration) | It will make a standard toast which will contain only simple text view. |
Void | show() | Show the toast view for specific duration. |
void | cancel() | Close the toast view if it is presently showing or will not show if it is not showing yet. |
Int | getDuaration() | Return the duration of toast which is already set. |
int | getGravity() | Get the location where the notification should appear on the screen. |
Float | getHorizontalMargin() | Returns the horizontal margin for Toast view |
Float | getVerticalMargin() | Returns the vertical margin for the Toast view |
View | getView() | Returns the Toast view Object. |
Int | getXOffset() | Returns the Y-axis offset of gravity’s location in number of pixels. |
Int | getYOffset() | Returns the X-axis offset of gravity’s location in number of pixels. |
Void | setDuration(int duration) | Set the duration for displaying the toast view. |
Void | setGravity(int gravity, intxOffset, intyOffset) | Set the location of toast view with x,y offset |
Void | setMargin(float horizontalMargin, verticalMargin) | Ser the margin of the Toast view. |
Void | setText(CharSequencecs) | Set the text message should be displayed in toast as given CharacterSequence |
Void | setText(intresourceID) | Set the text message should be displayed in toast as given String resource id. |
Void | setView(View view) | Set the view to show inside the toast. |
Constance values for the duration of toast that how long it should be displayed are
LENGTH_LONG and LENGTH_SHORT
Now let us create a simple android Toast example. So create a new Project named SimpleToast.
Open the MainActivity.java and inside the onCreate() method create a simple Toast object.
Toast simpleToast = Toast.makeText(getApplicationContext(), "simple Toast with Default Parameters", Toast.LENGTH_LONG);
Above will create a simple Toast.
Now we will set the Text of the Toast in following manner.
simpleToast.setText("Simple & Default");
Remember that you can use setText() method only if you’ve created your toast using makeText() method. Because setText() method is supposed to only change the current text not create a new text.
Now show your text using show() method.
simpleToast.show();
If you want to see output then you can Run the project.
Output will be like this.
Now we will create a new Toast which position will be different suppose I want to create a toast on the TOP LEFT corner. Then we can use setGravity() method.
It will take first argument gravity. Second is X-axis Offset from gravity and third is for Y-axis Offset from gravity point. So for the top left corner I will write my code like following.
Toast topLeft = Toast.makeText(getApplicationContext(), "Top Left Toast", Toast.LENGTH_LONG); topLeft.setGravity(Gravity.TOP | Gravity.LEFT, 10, 50); topLeft.show();
So it will give me the following output.
You can Change the Gravity as you want For Example
TOP, LEFT, RIGHT, CENER, BOTTOM, CENTER_VERTICAL, CENTER_HORIZONTAL etc.
Now We Will Add our custom view to the Toast view. So for displaying a custom View we will make one layout xml file.
So here I’m going to make one xml file with linear layout which will have horizontal orientation and also have one image and text view.
Right click on layout folder-> new->other…->android->Androi XML Layout File.
I’ll make a layout file named mytoast_layout.xml with Linear Layout with horizontal file.
Remember that you also have to give id of linear layout, mine is
mytoast_layout_view which have one image imageView1 and Text as txtMessage. And looks like following.
layout/mytoast_layout.xml
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mytoast_layout_view" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000000" android:orientation="horizontal" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/> <TextView android:id="@+id/txtMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textAppearance="?android:attr/textAppearanceMedium"/> </LinearLayout>
To get the View in my Class MainActivity I’m using LayoutInflater. So it’s inflate method will generate layout with ViewGroup (hear with linear layout which we have created) in following manner.
LayoutInflaterinflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.mytoast_layout, (ViewGroup) findViewById(R.id.mytoast_layout_view));
After this I’ll set the text of txtMessage defined in that mytoast_layout.xml like…
<pre”>TextViewtext = (TextView) layout.findViewById(R.id.txtMessage); text.setText(“This is a custom toast”);
Now create the Toast and make set the view which we’ve created using setView() method.
Toast toast = newToast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show();
So the Whole Code will be like this.
MainActivity.java
package org.miscellaneousvalley.simpletoast; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast simpleToast = Toast.makeText(getApplicationContext(), "simple Toast with Default Parameters", Toast.LENGTH_LONG); simpleToast.setText("Simple & Default"); simpleToast.show(); Toast topLeft = Toast.makeText(getApplicationContext(), "Top Left Toast", Toast.LENGTH_LONG); topLeft.setGravity(Gravity.TOP | Gravity.LEFT, 10, 50); topLeft.show(); LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.mytoast_layout, (ViewGroup) findViewById(R.id.mytoast_layout_view)); TextViewtext = (TextView) layout.findViewById(R.id.txtMessage); text.setText("This is a custom toast"); Toast toast = newToast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItemitem) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. intid = item.getItemId(); if (id == R.id.action_settings) { returntrue; } return super.onOptionsItemSelected(item); } }
Activity_main.xml
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="org.miscellaneousvalley.simpletoast.MainActivity"> </RelativeLayout>
mytoast_layout.xml
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mytoast_layout_view" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000000" android:orientation="horizontal"> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/> <TextView android:id="@+id/txtMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textAppearance="?android:attr/textAppearanceMedium"/> </LinearLayout>
That’s it save it and Run it! And see the output.