35

私のアプリでは、アクティビティ用のカレンダーウィジェットを作成し、前月または翌月にスクロールすると、乾杯して表示します。

問題は、トーストを表示するのに時間が必要です。たとえば、「2012/05」と「2012/06」にスクロールして「2012/07」にスクロールすると、十分に速くスクロールすると、待機する必要があります。 「2012/05」、「2012/06」、「2012/07」のトーストを1つずつゆっくりと見せていきます。

Androidにはトーストを管理するための目に見えないキューがあるようです

どうすればそれをきれいにして最後のトーストだけを表示できますか?特定のトーストを待たずにすぐに見せることはできますか?

「android.widget.Toast.java」を検索してメソッドを見つけましたcancel()が、残念ながら次のようには動作しません。

if (t != null) {
    t.cancel();
}
t = Toast.makeText(this.mContext, mHelper.getYear() + "年"
                + (mHelper.getMonth() + 1) + "月", Toast.LENGTH_SHORT);
t.show();
4

12 に答える 12

24

次のように「トースト」変数を宣言する必要があります。

Toast toastMessage;

次に、関数で次のようにします。

if (toastMessage!= null) {
    toastMessage.cancel();
}
toastMessage= Toast.makeText(context, "The message you want to display", duration);
toastMessage.show();
于 2015-08-10T14:12:31.877 に答える
23

ここに別の同様の質問からコピーされた私の答えがあります:

クラスはBoastあなたが必要とすることを正確に達成します。最新のコードは、GitHubの次の場所にあります。


秘訣は、最後に表示されたものを追跡しToast、それをキャンセルすることです。

私が行ったことはToast、最後に表示されたトーストへの静的参照を含むラッパーを作成することです。

新しいものを表示する必要がある場合は、新しい参照を表示する(そして静的に保存する)前に、まず静的参照をキャンセルします。

これが私が作成したラッパーの完全なコードですBoast-それは私がそれを使用するのに十分なToastメソッドを模倣しています。デフォルトでは、Boastは前のトーストをキャンセルするため、表示されるのを待っているトーストのキューを作成しません。

アプリを終了するときに通知をキャンセルする方法を知りたいだけの場合は、そこにたくさんのヘルプがあります。


package mobi.glowworm.lib.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.widget.Toast;

import java.lang.ref.WeakReference;

/**
 * {@link Toast} decorator allowing for easy cancellation of notifications. Use this class if you
 * want subsequent Toast notifications to overwrite current ones. </p>
 * <p/>
 * By default, a current {@link Boast} notification will be cancelled by a subsequent notification.
 * This default behaviour can be changed by calling certain methods like {@link #show(boolean)}.
 */
public class Boast {
    /**
     * Keeps track of certain Boast notifications that may need to be cancelled. This functionality
     * is only offered by some of the methods in this class.
     * <p>
     * Uses a {@link WeakReference} to avoid leaking the activity context used to show the original {@link Toast}.
     */
    @Nullable
    private volatile static WeakReference<Boast> weakBoast = null;

    @Nullable
    private static Boast getGlobalBoast() {
        if (weakBoast == null) {
            return null;
        }

        return weakBoast.get();
    }

    private static void setGlobalBoast(@Nullable Boast globalBoast) {
        Boast.weakBoast = new WeakReference<>(globalBoast);
    }


    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Internal reference to the {@link Toast} object that will be displayed.
     */
    private Toast internalToast;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Private constructor creates a new {@link Boast} from a given {@link Toast}.
     *
     * @throws NullPointerException if the parameter is <code>null</code>.
     */
    private Boast(Toast toast) {
        // null check
        if (toast == null) {
            throw new NullPointerException("Boast.Boast(Toast) requires a non-null parameter.");
        }

        internalToast = toast;
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Make a standard {@link Boast} that just contains a text view.
     *
     * @param context  The context to use. Usually your {@link android.app.Application} or
     *                 {@link android.app.Activity} object.
     * @param text     The text to show. Can be formatted text.
     * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or
     *                 {@link Toast#LENGTH_LONG}
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text, int duration) {
        return new Boast(Toast.makeText(context, text, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the text from a resource.
     *
     * @param context  The context to use. Usually your {@link android.app.Application} or
     *                 {@link android.app.Activity} object.
     * @param resId    The resource id of the string resource to use. Can be formatted text.
     * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or
     *                 {@link Toast#LENGTH_LONG}
     * @throws Resources.NotFoundException if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId, int duration)
            throws Resources.NotFoundException {
        return new Boast(Toast.makeText(context, resId, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view. Duration defaults to
     * {@link Toast#LENGTH_SHORT}.
     *
     * @param context The context to use. Usually your {@link android.app.Application} or
     *                {@link android.app.Activity} object.
     * @param text    The text to show. Can be formatted text.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text) {
        return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the text from a resource.
     * Duration defaults to {@link Toast#LENGTH_SHORT}.
     *
     * @param context The context to use. Usually your {@link android.app.Application} or
     *                {@link android.app.Activity} object.
     * @param resId   The resource id of the string resource to use. Can be formatted text.
     * @throws Resources.NotFoundException if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId) throws Resources.NotFoundException {
        return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Show a standard {@link Boast} that just contains a text view.
     *
     * @param context  The context to use. Usually your {@link android.app.Application} or
     *                 {@link android.app.Activity} object.
     * @param text     The text to show. Can be formatted text.
     * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or
     *                 {@link Toast#LENGTH_LONG}
     */
    public static void showText(Context context, CharSequence text, int duration) {
        Boast.makeText(context, text, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the text from a resource.
     *
     * @param context  The context to use. Usually your {@link android.app.Application} or
     *                 {@link android.app.Activity} object.
     * @param resId    The resource id of the string resource to use. Can be formatted text.
     * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or
     *                 {@link Toast#LENGTH_LONG}
     * @throws Resources.NotFoundException if the resource can't be found.
     */
    public static void showText(Context context, int resId, int duration)
            throws Resources.NotFoundException {
        Boast.makeText(context, resId, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view. Duration defaults to
     * {@link Toast#LENGTH_SHORT}.
     *
     * @param context The context to use. Usually your {@link android.app.Application} or
     *                {@link android.app.Activity} object.
     * @param text    The text to show. Can be formatted text.
     */
    public static void showText(Context context, CharSequence text) {
        Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the text from a resource.
     * Duration defaults to {@link Toast#LENGTH_SHORT}.
     *
     * @param context The context to use. Usually your {@link android.app.Application} or
     *                {@link android.app.Activity} object.
     * @param resId   The resource id of the string resource to use. Can be formatted text.
     * @throws Resources.NotFoundException if the resource can't be found.
     */
    public static void showText(Context context, int resId) throws Resources.NotFoundException {
        Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Close the view if it's showing, or don't show it if it isn't showing yet. You do not normally
     * have to call this. Normally view will disappear on its own after the appropriate duration.
     */
    public void cancel() {
        internalToast.cancel();
    }

    /**
     * Show the view for the specified duration. By default, this method cancels any current
     * notification to immediately display the new one. For conventional {@link Toast#show()}
     * queueing behaviour, use method {@link #show(boolean)}.
     *
     * @see #show(boolean)
     */
    public void show() {
        show(true);
    }

    /**
     * Show the view for the specified duration. This method can be used to cancel the current
     * notification, or to queue up notifications.
     *
     * @param cancelCurrent <code>true</code> to cancel any current notification and replace it with this new
     *                      one
     * @see #show()
     */
    public void show(boolean cancelCurrent) {
        // cancel current
        if (cancelCurrent) {
            final Boast cachedGlobalBoast = getGlobalBoast();
            if ((cachedGlobalBoast != null)) {
                cachedGlobalBoast.cancel();
            }
        }

        // save an instance of this current notification
        setGlobalBoast(this);

        internalToast.show();
    }

}
于 2013-04-19T11:25:04.673 に答える
17

正しいオブジェクトでメソッドを呼び出す必要があります。

toastObject.cancel()
于 2012-04-09T08:28:10.417 に答える
7

これがコードです。

final Toast toastobject = Toast.makeText(context, "This message will disappear when toast.close(); is called", Toast.LENGTH_SHORT);

これで、toastobjectのオブジェクトを使用できます。そのリファレンス

toastobject.cancel();

スレッドで、またはトーストを閉じたいときにいつでも使用できます。

于 2012-04-09T07:24:21.227 に答える
6

トーストを再利用できます。これにより、すぐに表示されます。

myToast.setText(toastMsg);
myToast.show();
于 2014-12-19T16:09:58.440 に答える
3

別のトーストを表示したいときに、前のトーストをキャンセルする方法はたくさんあります。以下に、それを実装するための最も簡単で簡単な方法を書きました。まず、クラス全体でアクセスできる変数を作成する必要があります。

private Toast toast;

クラス全体でアクセスできる変数を作成した後、トーストメッセージを表示し、前のトーストが表示されているかどうかを確認してキャンセルするメソッドをクラスに作成する必要があります。

   public void showToast(String message) {
    if (toast != null) {
        toast.cancel();
    }
    toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
    toast.show();
}

上記のメソッドを実行時に呼び出すことで、トーストメッセージを変更できます。

showToast("message 1");

//その後しばらくして

showToast("message 2");

それが役に立てば幸い。

于 2018-06-25T09:25:46.277 に答える
1

Toastには、現在のToastメッセージを非表示にする方法があります

public void cancel() {
    mTN.hide();
}

必要に応じてt.cancel()を呼び出してみてください。

于 2012-04-09T07:24:41.333 に答える
1

静的メソッドを作成し、それを使用してトーストを表示できます。

public static Toast toast = null;
public static showToast(Context context,String msg){
if(toast!=null)             //this will cancel the toast on the screen if one exists
   toast.cancel();
toast = Toast.makeText(context,msg);
toast.show();
}
于 2015-06-27T16:11:41.463 に答える
1

単純。別のトーストを作成したい場合は、トーストでメソッド.cancel()を呼び出すだけです。

このようにクラスの先頭にToast変数を定義することから始めます

private Toast mToast;

後で、新しいトーストを作成したい(そして古いトーストを消したい)ときは、これを行います。

if(mToast != null) {
  mToast.cancel();  //if a toast exists it deletes it, allowing you to create a new one
}


mToast = Toast.makeText(this, "This will show up now!", Toast.LENGTH_LONG);
mToast.show(); //creates the new toast. 
于 2017-05-29T07:56:31.287 に答える
0
public static Toast  sToast=null;

// create Toast object;

public void showToast(String msg)

    {

    //here is checking whether toast object is null or not;if not null gonna cancel the toast that is showing in phone window and make it null;  

    if(sToast!=null)
    {

      sToast.cancel;

    sToast=null;
    }

    //if toast object is null,gonna create new instance and make it shown on phone window.

    if(sToast==null)
    {

        sToast=Toast.makeText(currentActivity.this,msg,Duration);

        sToast.setGravity();

        sToast.show();

    }

}
于 2015-10-09T07:45:46.500 に答える
0

遅ればせながら:コードが機能しない理由は、作成中のコードToast.makeText()への参照が返されないためToastです。これは、すばやく簡単に作成できるように設計された単なるヘルパーメソッドですがToast、参照やキャンセルはできません。キャンセルするには、次のことを行う必要があります。

t=Toast(requireContext())
t.setText(YOUR TEXT)
t.setDuration(1000)
t.show()

このようにして、コンストラクターが呼び出されたときにtに参照が割り当てられ、後でキャンセルできるようになります。

于 2021-11-11T04:15:12.640 に答える
-1

ワンシュートテクニックを使用できます。Oke定義を始めましょう:

private Toast mToast;
private showOnce=false;

後でトーストを一度見せたいとき:

if(showOnce==false){
  mToast=Toast.makeText(this, "Once!", Toast.LENGTH_LONG);
  mToast.show();
  showOnce=true;
}
于 2017-08-27T18:03:19.377 に答える