How to cancel Toast
Solution 1:
Toast.makeText
returns a Toast
object. Call cancel()
on this object to cancel it.
Solution 2:
The shortest duration you can specify for the toast is Toast.LENGTH_SHORT
which has a value of 0
but is actually 2000 milliseconds long
. If you want it shorter than that, then try this:
final Toast toast = Toast.makeText(ctx, "This message will disappear in 1 second", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 1000); //specify delay here that is shorter than Toast.LENGTH_SHORT
Solution 3:
I think there is no need to create a custom toast.
Create only single instance of the Toast
class. We just set the text of the toast using toast.setText("string")
, and call toast.cancel()
method in onDestroy()
method.
Working code snippet as follows:
package co.toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ShowToastActivity extends Activity {
private Toast toast = null;
Button btnShowToast;
@SuppressLint("ShowToast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// creates only one toast object..
toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
btnShowToast = (Button) findViewById(R.id.btnShowToast);
btnShowToast.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// only set text to toast object..
toast.setText("My toast!");
toast.show();
}
});
}
@Override
protected void onDestroy()
{
toast.cancel();
super.onDestroy();
}
@Override
protected void onStop () {
super.onStop();
toast.cancel();
}
}
Hope this helpful to you..