Saturday, June 6, 2015

// //

Auto-close Alert dialog programmatically

What is AlertDialog?
An Alertdialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.
 What are we going to do? 
This time we will close the alertdialog programmatically because not like Toast which is auto closed after 1-2 seconds, Dialog by default is not auto closed and doesn’t have any settings for auto closing. If ever, you want your Dialog to be programmatically close then you may use a Timer to achieve it. Here a sample:

    
And then Click the Button:
close alertdialog programmatically android
The alertdioalog will close after 5 seconds
activity_main.xml

    
MainActivity.java
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // get button
        Button btnShow = (Button)findViewById(R.id.showdialog);
        btnShow.setOnClickListener(new View.OnClickListener() {
 
         //on click listener
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle("How to close alertdialog programmatically");
                builder.setMessage("5 second dialog will close automatically");
                builder.setCancelable(true);
               
                final AlertDialog closedialog= builder.create();
 
                closedialog.show();
 
                final Timer timer2 = new Timer();
                timer2.schedule(new TimerTask() {
                    public void run() {
                     closedialog.dismiss(); 
                        timer2.cancel(); //this will cancel the timer of the system
                    }
                }, 5000); // the timer will count 5 seconds....
 
            }
        });
    }
}


You may also like : Alertdialog Media Player, Start, Stop(How To Set MediaPlayer Volume Programmatically?)