show toast in UI thread - Android android.widget

Android examples for android.widget:Toast

Description

show toast in UI thread

Demo Code

import android.app.Activity;
import android.view.Gravity;
import android.widget.Toast;

public class Main {

  public static void show(final Activity activity, final String message) {
    showAtCenter(activity, message, false);
  }//from w  ww  .  j ava2  s .com

  public static void show(Activity activity, int msgResID) {
    show(activity, activity.getResources().getString(msgResID));
  }

  public static void showAtCenter(final Activity activity, final String message, final boolean center) {

    activity.runOnUiThread(new Runnable() {
      public void run() {
        Toast toast = Toast.makeText(activity, message, Toast.LENGTH_SHORT);
        if (center)
          toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
      }
    });
  }

}

Related Tutorials