Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop all toast messages when going to another screen in Android

Tags:

android

toast

enter image description here enter image description here

I am displaying a simple Toast when I click a button. My issue is, when I click on a button multiple times, that Toast message keeps displaying until I get to the main screen. I would like to stop the Toast when I get to the main screen and kill the Toast message in the corresponding activity. I have attached a screenshot.

I have written code as follows:

public class Main extends Activity {

    Dialog d;
    Toast t;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                t = Toast.makeText(Main.this, "you clicked on button!", Toast.LENGTH_LONG);
                t.show();
            }
        });
    }
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        t.cancel();
    }
}

How can I do it?

like image 706
prasad.gai Avatar asked Mar 14 '11 07:03

prasad.gai


2 Answers

Hi I have the same problem. The problem is that the Toast overlaps e.g. if you press 10 times the Toast will stay 10 x LENGTH_SHORT. The only solution I came with was to control the time the Toast is shown by myself. When you show a Toast just keep a track of the last time you show it, it's still on the screen don't show it again. In your worst case the Toast will be visible only LENGTH_SHORT time.

like image 108
Mojo Risin Avatar answered Sep 28 '22 09:09

Mojo Risin


Toast.makeText returns a Toast object. You can call cancel() on this object to cancel it, then show the new one.

like image 33
mihail Avatar answered Sep 28 '22 09:09

mihail