cancel()
のメソッドを使用してToast
、表示中のトーストを閉じることができます。
変数を使用して、表示するすべての Toast への参照を保持し、cancel()
別の Toast を表示する前に呼び出すだけです。
private Toast mToast = null; // <-- keep this in your Activity or even in a custom Application class
//... show one Toast
if (mToast != null) mToast.cancel();
mToast = Toast.makeText(context, text, duration);
mToast.show();
//... show another Toast
if (mToast != null) mToast.cancel();
mToast = Toast.makeText(context, text, duration);
mToast.show();
// and so on.
次のように、それを小さなクラスにラップすることもできます。
public class SingleToast {
private static Toast mToast;
public static void show(Context context, String text, int duration) {
if (mToast != null) mToast.cancel();
mToast = Toast.makeText(context, text, duration);
mToast.show();
}
}
次のようにコードで使用します。
SingleToast.show(this, "Hello World", Toast.LENGTH_LONG);
///