Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Display a toast message after a custom time when a button is clicked

Tags:

android

xml

toast

I want to add a toast say after 30 seconds when a button is clicked. Can you please help me out.

like image 581
Emm Jay Avatar asked Oct 28 '25 19:10

Emm Jay


2 Answers

You can use a Handler with postDelayed(). You can find the documentation here

For example:

new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

             // Put your Toast here

        }
}, 30 * 1000);

You have to watch out which Thread your Handler is running on. If you want to make UI modifications (like the Toast), you have to attach the Handler on your UI-Thread.

like image 116
super-qua Avatar answered Oct 30 '25 10:10

super-qua


Something like that:

Button button = new Button(this);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, "Hello!", Toast.LENGTH_LONG).show();
            }
        }, 30000);

    }
});
like image 40
nikis Avatar answered Oct 30 '25 10:10

nikis