Android UI How to - Display a Toast








Question

We would like to know how to display a Toast.

Answer

The following code is a convenient method to show a Toast.

It wraps the Toast show method in the UI thread.

/*from  w  w w.  jav a2  s  .  c  o m*/
import android.app.Activity;
import android.widget.Toast;
public class Main {
  public static void displayToast(final Activity activity, final String text,
      final int duration) {
    activity.runOnUiThread(new Runnable() {

      public void run() {
        Toast toast = Toast.makeText(activity, text, duration);
        toast.show();

      }
    });
  }
}