Android                
            トースト
        
        
            
    サーチ…
前書き
Toastは小さなポップアップで操作に関する簡単なフィードバックを提供し、タイムアウト後自動的に消えます。メッセージに必要なスペースだけを満たし、現在のアクティビティは表示され、インタラクティブなままです。
構文
- トーストmakeText(コンテキストコンテキスト、CharSequenceテキスト、int継続時間)
 - トーストmakeText(コンテキストコンテキスト、int resId、int duration)
 - void setGravity(int重力、int xOffset、int yOffset)
 - void show()
 
パラメーター
| パラメータ | 詳細 | 
|---|---|
| コンテキスト | あなたのToastを表示するためのコンテキスト。 thisは一般にアクティビティで使用され、 getActivity()は一般的にフラグメントで使用されます | 
| テキスト | Toastに表示されるテキストを指定するCharSequenceです。 CharSequenceを実装するオブジェクトはすべて使用できます。文字列 | 
| resId | Toastに表示するリソースStringを提供するために使用できるリソースID。 | 
| 期間 | トーストが表示される時間を表す整数のフラグ。オプションはToast.LENGTH_SHORTとToast.LENGTH_LONG  | 
| 重力 | トーストの位置または重力を指定する整数。 ここのオプションを見る | 
| xOffset | トースト位置の水平オフセットを指定します。 | 
| yオフセット | トースト位置の垂直オフセットを指定します。 | 
備考
トーストは小さなポップアップで操作に関する簡単なフィードバックを提供します。メッセージに必要なスペースだけを満たし、現在のアクティビティは表示され、インタラクティブなままです。
最近のToastの代わりにSnackBarがあります。 SnackBarは更新されたビジュアルスタイルを提供し、ユーザーはメッセージを閉じたり、さらにアクションを起こすことができます。詳細については、 SnackBarのマニュアルを参照してください。
公式文書:
https://developer.android.com/reference/android/widget/Toast.html
トーストの位置を設定する
標準的なトースト通知が、画面の下部に水平の中央に揃って表示されます。この位置はsetGravity(int, int, int)変更できます。これは、重力定数、x位置オフセット、およびy位置オフセットの3つのパラメータを受け入れます。 
たとえば、トーストが左上隅に表示されるようにする場合は、次のように重力を設定できます。
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
        トーストメッセージを表示する
Androidでは、Toastはユーザーにコンテキストによるフィードバックを与えるために使用できる単純なUI要素です。
簡単なToastメッセージを表示するには、次の操作を行います。
// Declare the parameters to use for the Toast
Context context = getApplicationContext(); 
// in an Activity, you may also use "this"
// in a fragment, you can use getActivity()
CharSequence message = "I'm an Android Toast!";
int duration = Toast.LENGTH_LONG; // Toast.LENGTH_SHORT is the other option
// Create the Toast object, and show it!
Toast myToast = Toast.makeText(context, message, duration);
myToast.show();
 または、Toastオブジェクトを保持せずにToastインラインを表示するには、次の操作を実行します。
Toast.makeText(context, "Ding! Your Toast is ready.", Toast.LENGTH_SHORT).show();
  重要: show()メソッドがUIスレッドから呼び出されていることを確認してください。別のスレッドからToastを表示しようとしている場合は、たとえば、 Activity runOnUiThreadメソッドを使用できます。 
そうしないと、Toastを作成してUIを変更しようとすると、 RuntimeExceptionがスローされ、 RuntimeExceptionようになります。 
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
 この例外を処理する最も簡単な方法は、runOnUiThreadを使用することです。構文は次のとおりです。
   runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // Your code here
        }
    });
        カスタムトーストの作成
デフォルトのToastビューを使用しない場合は、 Toastオブジェクトに対してsetView(View)メソッドを使用して独自のトーストビューを提供できます。 
まず、Toastで使用したいXMLレイアウトを作成します。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:background="#111">
    <TextView android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"/>
    <TextView android:id="@+id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"/>
</LinearLayout>
 次に、Toastを作成するときにXMLからカスタムViewを展開し、 setViewを呼び出しsetView 
// Inflate the custom view from XML
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_layout,
                               (ViewGroup) findViewById(R.id.toast_layout_root));
// Set the title and description TextViews from our custom layout
TextView title = (TextView) layout.findViewById(R.id.title);
title.setText("Toast Title");
TextView description = (TextView) layout.findViewById(R.id.description);
description.setText("Toast Description");
// Create and show the Toast object
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
        Toast(アプリケーションワイド)を表示するスレッドセーフな方法
public class MainApplication extends Application {
    
    private static Context context; //application context
    private Handler mainThreadHandler;
    private Toast toast;
    public Handler getMainThreadHandler() {
        if (mainThreadHandler == null) {
            mainThreadHandler = new Handler(Looper.getMainLooper());
        }
        return mainThreadHandler;
    }
    @Override public void onCreate() {
        super.onCreate();
        context = this;
    }
       
    public static MainApplication getApp(){
        return (MainApplication) context;
    }
    /**
     * Thread safe way of displaying toast.
     * @param message
     * @param duration
     */
    public void showToast(final String message, final int duration) {
        getMainThreadHandler().post(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(message)) {
                    if (toast != null) {
                        toast.cancel(); //dismiss current toast if visible
                        toast.setText(message);
                    } else {
                        toast = Toast.makeText(App.this, message, duration);
                    }
                    toast.show();
                }
            }
        });
    }
  MainApplicationをmanifestに追加することを忘れないでください。 
これでトーストメッセージが表示されます。
MainApplication.getApp().showToast("Some message", Toast.LENGTH_LONG);
        ソフトキーボードの上にトーストメッセージを表示する
デフォルトでは、キーボードが表示されていてもAndroidの画面下部にToastメッセージが表示されます。これにより、キーボードのすぐ上にトーストメッセージが表示されます。
public void showMessage(final String message, final int length) {
    View root = findViewById(android.R.id.content);
    Toast toast = Toast.makeText(this, message, length);
    int yOffset = Math.max(0, root.getHeight() - toast.getYOffset());
    toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, yOffset);
    toast.show();
}
        トーストメッセージを表示するスレッドセーフな方法(AsyncTaskの場合)
アプリケーションを拡張し、トーストメッセージのスレッドを安全に保ちたくない場合は、AsyncTasksのpost executeセクションに必ず表示してください。
public class MyAsyncTask extends AsyncTask <Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        // Do your background work here
    }
    @Override
    protected void onPostExecute(Void aVoid) {
        // Show toast messages here
        Toast.makeText(context, "Ding! Your Toast is ready.",   Toast.LENGTH_SHORT).show();
    }
    
}