ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How To Toast In Android

Updated on February 10, 2018

With 70 million phones sold worldwide, the Android OS provides a great opportunity for developers to make a little extra money. Programmers can do so by writing applications and putting them on the marketplace. This is just one article right now but I plan to write a more intricate development hub in the future. At the bottom I have included the complete source code for a simple app that displays a custom toast in Android.

When developing an Android app, a very useful tool for displaying a message to the user is a toast. A toast in Android is basically just a small popup message that only uses the minimum space required to display the message and disappears after a set amount of time. For those of you who don't have an Android device, it's the thing that says "Data Saved!" in the picture below.

So without further delay, let's learn to toast in Android.

Simple Text Toast In Android

Context context = getApplicationContext();
CharSequence message = "Data Saved!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, message, duration);		
toast.show();
Toast In Android
Toast In Android

Okay, so above here is the code to create a simple text toast in Android. As you can see, we defined three variables of type Context, CharSequence and Integer. These represent the variables that must be passed into Toast.makeText() to instantiate the Toast object.

The getApplicationContext() method returns the context of the single, global Application object of the current process. Technically, we could have used the keyword (this) in it's place. The second variable is simply the message we want the toast to display and the third variable is how long the message will be displayed for in milliseconds. In this case we use a default value, Toast.LENGTH_SHORT, but we could have also just wrote 2000.

Line 5 is where we create our toast in Android.

Lastly, in order to actually see what we have created we must call the show() method. We do so by writing toast.show();


Positioning Our Toast In Android

If we wanted to change the position at which our toast appears we can do so quite easily by adding:

toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

This will center the toast vertically. Increasing the second and third values will move the toast slightly, however, the default locations are usually adequate.


Custom toast in Android
Custom toast in Android

Custom Toast In Android

To create a custom toast in Android, we must first add an XML file call toast_layout.xml to the res/layout directory. The XML code we are going to put in this file is located below. This will create our toast, now we just have to add some Java and a picture.

The Java code for this section is located below. Alright, so we want to retrieve the LayoutInflater with getLayoutInflater(), and then inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout resource ID and the second is the root View. You can use this inflated layout to find more View objects in the layout, so now capture and define the content for the ImageView and TextView elements. Finally, create a new Toast with Toast(Context) and set some properties of the toast, such as the gravity and duration. Then call setView(View) and pass it the inflated layout. You can now display the toast in Android with your custom layout by calling show()

Custom Toast In Android - toast_layout.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              android:background="#DAAA"
              >
    <ImageView android:id="@+id/image"
               android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF"
              />
</LinearLayout>

Custom Toast In Android - Java

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
                               (ViewGroup) findViewById(R.id.toast_layout_root));

ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Data has been saved!");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

Full Code: Toast In Android Java File

import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;

public class StorageActivity extends Activity implements View.OnClickListener{
	Button save;
	EditText name;
	EditText addr;
	String nam, add;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        save = (Button) findViewById(R.id.save);
    	name = (EditText) findViewById(R.id.name);
    	addr = (EditText) findViewById(R.id.addr);
        
        save.setOnClickListener(this);
    }

    @Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		nam = name.getText().toString();
		add = addr.getText().toString();
		
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_layout,
		                               (ViewGroup) findViewById(R.id.toast_layout_root));

		ImageView image = (ImageView) layout.findViewById(R.id.image);
		image.setImageResource(R.drawable.icon);
		TextView text = (TextView) layout.findViewById(R.id.text);
		text.setText("Data has been saved!");

		Toast toast = new Toast(getApplicationContext());
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layout);
		toast.show();
		
	}
}

Full Code: Toast In Android XML File - main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	android:id="@+id/LinearLayout1"
xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    
    <TextView 
    	android:layout_alignParentLeft="true" 
    	android:layout_alignBaseline="@+id/name" 
    	android:layout_alignParentTop="true" 
    	android:text="Name:" 
    	android:id="@+id/textView1" 
    	android:layout_width="wrap_content" 
    	android:layout_height="wrap_content">
    </TextView>
    	
    <EditText 
    	android:layout_toRightOf="@+id/textView1" 
    	android:layout_alignParentRight="true" 
    	android:layout_alignParentTop="true" 
	    android:layout_weight="1" 
	    android:layout_width="wrap_content" 
	    android:layout_height="wrap_content" 
	    android:id="@+id/name">
    	<requestFocus></requestFocus>
    </EditText>
    
    <TextView 
	    android:layout_alignParentLeft="true" 
	    android:layout_alignBaseline="@+id/addr" 
	    android:layout_below="@+id/name" 
	    android:layout_marginTop="22dp" 
	    android:text="Address:" 
	    android:id="@+id/textView2" 
	    android:layout_width="wrap_content" 
	    android:layout_height="wrap_content">
	</TextView>
	
    <EditText 
	    android:layout_toRightOf="@+id/textView2" 
	    android:layout_alignParentRight="true" 
	    android:layout_below="@+id/name" 
	    android:layout_weight="1" 
	    android:layout_width="wrap_content" 
	    android:layout_height="wrap_content" 
	    android:id="@+id/addr">
	</EditText>
	
    <Button 
	    android:layout_width="match_parent" 
	    android:text="Save" 
	    android:layout_height="wrap_content"
	    android:onClick="onClick" 
	    android:id="@+id/save" 
	    android:layout_alignParentBottom="true" 
	    android:layout_alignParentLeft="true">
	</Button>
	
</RelativeLayout>

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)