Singleton Toast

On Android you may have experienced delayed toasts or overlapping toasts. This causes the toasts being displayed with irrelevant context/activity (e.g. user may have pressed backed, or previous toast is still overriding new one, or when too many toasts are displayed on screen).

Consider the code below. It defines a single function for toast, that makes use of context object of Application. The class MyApplication needs to be declared in manifest.xml. The main advantage of such design is

  • reduced footprint for activity’s context object.
  • at any moment only one toast remains on screen
  • reusing single toast object, rather than creating for each show.


public class MyApplication extends Application {

	private static Resources resources;
	private static Context context;
	
	private static Toast toast;

	/**
	 * Called when the application is starting, before any other application
	 * objects have been created. Implementations should be as quick as possible
	 * (for example using lazy initialization of state) since the time spent in
	 * this function directly impacts the performance of starting the first
	 * activity, service, or receiver in a process. If you override this method,
	 * be sure to call super.onCreate().
	 * */
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i("MyApplication", "Starting app...");
		MyApplication.resources = getResources();
		MyApplication.context = getApplicationContext();
		
		MyApplication.toast = Toast.makeText(MyApplication.context, "", Toast.LENGTH_SHORT);
	}
	
	/** Returns the global resources object. */
	public static Resources getResourcesObject() {
		return MyApplication.resources;
	}

	/** Returns the global context object. */
	public static Context getContextObject() {
		return MyApplication.context;
	}

	public static void toast(String message)
	{
		MyApplication.toast(message, Toast.LENGTH_SHORT);
	}

	public static void toast(String message, int duration)
	{
		MyApplication.toast.cancel();
		MyApplication.toast.setText(message);
		MyApplication.toast.setDuration(duration);
		MyApplication.toast.show();
	}

}

Tagged on:

Leave a Reply

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