I developed an android application and I am facing a problem with Toast
.
Suppose I am displaying a Toast, it is displayed on the application window.
When a Dialog box is appears, the toast doesn't disappear instantly .
I want to know how I can cancel the toast.
Toast. makeText returns a Toast object. Call cancel() on this object to cancel it.
You can use toast. cancel() befor showing next toast. cancelling won't reduce the toast time.
Call cancel() on the Toast to get rid of it.
Toast.makeText
returns a Toast
object. Call cancel()
on this object to cancel it.
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..
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With