How to solve android Toast duplicate display

  • 2020-12-16 06:06:22
  • OfStack

Toast is a simple message prompt box, it can't get the focus, according to the time set to display will disappear automatically,1 generally used for help or prompt.

Let me share with you my solution:

You don't need to calculate the time of Toast, that is, you define a global member variable, Toast, which only goes to make when Toast is not null, or setText. To make Toast no longer appear immediately after the return key is pressed, override the parent class Activity's onBackPressed() method to remove cancel from your Toast.

Code:


private Toast mToast; 
public void showToast(String text) { 
if(mToast == null) { 
mToast = Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT); 
} else { 
mToast.setText(text); 
mToast.setDuration(Toast.LENGTH_SHORT); 
} 
mToast.show(); 
} 
public void cancelToast() { 
if (mToast != null) { 
mToast.cancel(); 
} 
} 
public void onBackPressed() { 
cancelToast(); 
super.onBackPressed(); 
} 

The solution to the Android Toast repetitive display wait time problem is described below

When the click event is triggered to display toast information, if the length of time is set as LENGTH_LONG, the toast information will still be displayed although it goes back to the background. Especially when clicking continuously, toast will queue until all toast is displayed. This interface has a very poor user experience.

→ 1 toast 2 toast 3 toast 4 toast 5 toast → 2 toast 4 toast 5 toast

To avoid this problem, a judgment can be added where toast information is displayed. The method is as follows:


private Context mcontext;
private Toast mtoast;
if(mtoast!=null)
{
mtoast.setText(R.string.neterror); 
}
else
{
/*
*  The first 1 The current context, with this or getApplicationContext() Said. 
*  The first 2 Parameters: display the string, using R.string Said. 
*  The first 3 Parameters: length of display time. with LENGTH_LONG( long ) or LENGTH_SHORT( short ) It can be expressed in milliseconds. 
*/
mtoast=Toast.makeText(mcontext,R.string.neterror, Toast.LENGTH_SHORT);
} 
mtoast.show(); // According to toast information 

You can also design your own Toast message box by setting other properties of Toast.


Related articles: