Learning Android toast the long way

By | June 11, 2017

It is relatively easy to show a toast (a short message that appears on screen for a few seconds and then disappears) with the following code:

Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_LONG ).show();

The trick is trying to understand how this short hand method was created. This is what it looks like written the long way:

Context context;
Toast toast;
context = getApplicationContext();
CharSequence myText = "hello";
int duration = Toast.LENGTH_LONG;

toast = Toast.makeText(context, myText, duration);
toast.show();

Let’s work backwards. The documentation (https://developer.android.com/reference/android/widget/Toast.html) shows the makeText method requires 3 arguments. Context, text and duration.

The text and duration are easy. Note that the duration is fixed to either LENGTH_LONG which is 3.5 seconds or LENGTH_SHORT which is 2 seconds. It cannot not be anything else like 5 or 11.

The trick is understanding the context. The context is obtained from the command getApplicationContext() which passes the required information to the Toast object so that it knows how to do stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *