Android – toast appears multiple times

In my application, click on the button I create a toast as –

Toast.makeText(context,"Please Enter Username",Toast.LENGTH_SHORT).show();

But when someone clicks the button 5-6 times and closes the application, or enters another screen, it will still continue to display toast on the other screen for some time. I've seen many of the same solutions

I tried –

toast = Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT);
        toast.show();

And canceled the toast –

onPause(){

if(toast!=null){
toast.cancel();

}

Same as ondestroy()

I hope that when anyone clicks the button 5-6 times and exits the application or the activity, the toast message should disappear. Or suggest any alternative solution

resolvent:

You can create a field variable and method that displays only one toast at a time:

Toast toast;

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

And cancel any existing toast when onpause() exits:

protected void onPause() {
    if(toast != null)
        toast.cancel();
    super.onPause();
}

Now, whenever you want to display toast, just call:

displayToast("Please Enter Username");

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>