Ответ 1
Вам нужно вызвать метод для правильного объекта.
toastObject.cancel()
В моем приложении я создаю виджет календаря для моей активности, когда я просматриваю его до предыдущего или следующего месяца, я позволяю ему делать тост и показывать его.
Вопрос в том, что тост нужно время, чтобы показать, когда я прокручиваю его достаточно быстро, например, я прокрутил до "2012/05" и "2012/06" и прокрутил до "2012/07" без паузы, я придется ждать Тоста "2012/05", "2012/06", "2012/07", чтобы показывать по очереди медленно.
Кажется, что у 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();
Вам нужно вызвать метод для правильного объекта.
toastObject.cancel()
Вот мой ответ, скопированный из другого подобного вопроса:
Класс 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 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();
}
}
Вам просто нужно объявить "Toast" var следующим образом:
Toast toastMessage;
Затем в вашей функции сделайте следующее:
if (toastMessage!= null) {
toastMessage.cancel();
}
toastMessage= Toast.makeText(context, "The message you want to display", duration);
toastMessage.show();
Вот код.
final Toast toastobject = Toast.makeText(context, "This message will disappear when toast.close(); is called", Toast.LENGTH_SHORT);
Теперь вы можете использовать Object toastobject. Его Reference
toastobject.cancel();
Вы можете использовать его в Thread или всякий раз, когда хотите закрыть Toast.
Вы можете повторно использовать тост, это немедленно отобразит его.
myToast.setText(toastMsg);
myToast.show();
У Toast есть способ скрыть текущее тост-сообщение
public void cancel() {
mTN.hide();
}
Попробуйте вызвать t.cancel(), когда это необходимо.
Вы можете создать статический метод и использовать его для отображения тоста:
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();
}
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();
}
}
Simple. Просто вызовите метод .cancel() на тосте, как только вы захотите создать другой тост.
Начните с определения переменной Toast в верхней части вашего класса, например
private Toast mToast;
Позже, Когда вы хотите создать новый Toast (и старый) исчезнет, сделайте это.
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.
Вы можете использовать одну технику съемки. Oke пусть начинает определять:
private Toast mToast;
private showOnce=false;
Позднее, когда вы хотите показать тост один раз:
if(showOnce==false){
mToast=Toast.makeText(this, "Once!", Toast.LENGTH_LONG);
mToast.show();
showOnce=true;
}