Android

Android Working With Dialogs

android alert dialogs
Written by Yasir Ameen

In Android, dialog is a small window that alert the user with different prompts information. Android includes number of dialogs which makes our application very responsive to the user. In this tutorial, i tried to show you that how you can create that dialogs.

Let’s Work With Dialogs

Before describing anything, see the attached video that what we are going to learn in this article.

 

Creating Simple Alert Dialog

Simple Alert Dialog is only showing a message text without any action button, to dismiss this touch anywhere or press back key.

 //Code Snippet For Alert Dialog
 Button _btn_alertDialog = (Button) findViewById(R.id.btn_alertdialog);
_btn_alertDialog.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setMessage("This is an Alert Dialog without any button. Touch any where on the screen to dismiss.")
                .setTitle("Welcom");

        AlertDialog dialog = builder.create();
        dialog.show();

    }
});

dialog

 

 

Creating Alert Dialog With Buttons

Alert Dialog with buttons gives us to take decision about something. We set Positive button for taking decision and Negative button for denying decision.

//Code Snippet For Alert Dialog With Action
Button _btn_alertDialogWithAction = (Button) findViewById(R.id.btn_alertwithactions);
_btn_alertDialogWithAction.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        //Set Message and Title
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setMessage("Do you really want to send information to the third party app.")
                .setTitle("Information");

        //Set When SEND Button Click
        builder.setPositiveButton("SEND", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                Toast.makeText(MainActivity.this, "Information Send Successfully!", Toast.LENGTH_SHORT).show();
            }
        });

        //Set When Cancel Button Click
        builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                //Dismissing the alertDialog
                dialogInterface.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }
});

Dialog

 

Creating Alert Dialog With List

Alert Dialog with list displaying a simple list for selection. We create String array for making list and pass this array into builder.setItems() methods.

//Code Snippet For Alert Dialog With List
final String[] country = {"PAKISTAN", "INDIA", "CHINA", "JAPAN"};
Button _btn_alertDialogWithList = (Button) findViewById(R.id.btn_alertwithlist);
_btn_alertDialogWithList.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Pick a Country")
                .setItems(country, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        String selectedCountry = country[i];
                        Toast.makeText(MainActivity.this, selectedCountry, Toast.LENGTH_SHORT).show();
                    }
                });

        AlertDialog dialog = builder.create();
        dialog.show();

    }
});

 

dialog

 

Creating Alert Dialog With Check Boxes

Check boxes is used to select multiple choices at a time. We define String array then pass this array to the builder.setMultiChoiceItems() method.

We are using ArrayList for storing checked items and then we are iterating all the items one by one from ArrayList.


//Code Snippet For Alert Dialog With Choices
final String[] items = {"Applied Maths","Applied Physics","Quantum Theory","Chemisty"};
final ArrayList<String> mselectedItems = new ArrayList<>();
Button _btn_alertDialogWithChoices = (Button) findViewById(R.id.btn_alertwithchoices);
_btn_alertDialogWithChoices.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        if (!mselectedItems.isEmpty()) {

            mselectedItems.clear();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose Your Subjects ")
                .setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {

                        //after selecting an items, saving them in an ArrayList
                        if (isChecked){

                            String selectedItems = items[which];
                            mselectedItems.add(selectedItems);
                        }
                    }
                })
                .setPositiveButton("DONE", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        //Iterating every item of ArrayList
                        for (String items : mselectedItems) {

                            Toast.makeText(MainActivity.this, "You Selected " + items, Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        dialogInterface.dismiss();
                    }
                });

        AlertDialog dialog = builder.create();
        dialog.show();
    }
});

dialog

 

 

Creating Alert Dialog With Check Radio Boxes

Radio box is used to select only one choice at a time. We also define String array then pass this array to the builder.setSingleChoiceItem() method.

 //Code Snippet For Alert Dialog Radio List
final String[] radioItems = {"Android","iPhone","Windows","BlackBerry"};
final String[] radioValue = {""};
Button _btn_alertDialogWithRadio = (Button) findViewById(R.id.btn_alertwithradio);
_btn_alertDialogWithRadio.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Select Your Brand")
                .setSingleChoiceItems(radioItems, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        String selectedValue = radioItems[i];
                        radioValue[0] = selectedValue;

                    }
                });

        builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                Toast.makeText(MainActivity.this, "Your Selected " +radioValue[0], Toast.LENGTH_SHORT).show();
                dialogInterface.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }
});

 

dialog

 

 

Creating Progress Dialog.

ProgressDialog is used when we want to make user wait until the task complete with some indication that something is happening by showing progress or by showing rotating circle which tells the user to wait.

We will use AsyncTask class in order to show progress. See my post AysncTask With Progress Dialog for understand about AsyncTask and its functionality.


public class MainActivity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        
        //Code Snippet For Showing ProgressDialog
        Button _btn_showingProgressDialog = (Button) findViewById(R.id.btn_alertwithprogress);
        _btn_showingProgressDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                progressTask task = new progressTask();
                task.execute();

            }
        });


    }

    public class progressTask extends AsyncTask<String,String,String> {

        ProgressDialog pd;
        @Override
        protected void onPreExecute() {

            pd = new ProgressDialog(MainActivity.this);
            pd.setTitle("Uploading");
            pd.setMessage("Please wait your file is being uploaded to the server.");
            pd.setIcon(R.drawable.loading);
            pd.setIndeterminate(false);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        protected String doInBackground(String... strings) {

            for (int i = 0; i < 7; i++) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "Uploading Complete";
        }

        @Override
        protected void onPostExecute(String s) {

            Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
            pd.dismiss();
        }
    }
}

progress dialog

 

Creating Custom Dialog

Creating Custom Layout

Android Dialog mechanism is also support custom dialog, if some one wants to show their own layout as dialog then he must create a layout. I am have created my layout and here is the xml code.

<pre><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#009688"
        android:id="@+id/view" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Custom Dialog"
        android:id="@+id/textView"
        android:gravity="center"
        android:textSize="35dp"
        android:textColor="#ffffff"
        android:layout_alignBottom="@+id/view"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:inputType="text"
        android:hint="Please Enter Your Name"
        android:drawableLeft="@drawable/ic_person_black_24dp"
        android:drawablePadding="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:singleLine="true"
        android:ems="10"
        android:id="@+id/txtusername"
        android:layout_below="@+id/view"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:inputType="textPassword"
        android:hint="Please Enter Your Password"
        android:drawableLeft="@drawable/ic_lock_black_24dp"
        android:drawablePadding="10dp"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:singleLine="true"
        android:ems="10"
        android:id="@+id/txtuserpass"
        android:layout_below="@+id/txtusername"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    
</RelativeLayout>

 

above xml code will produce following result.

 

android custom dialog

 

Writing Code For Showing Custom Dialog

We will use LayoutInflater class for inflating our custom layout.

Button _btn_showingCustomDialog = (Button) findViewById(R.id.btn_showingcutomdialog);
_btn_showingCustomDialog.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = getLayoutInflater();

        View dialog_layout = inflater.inflate(R.layout.custom_dialog_layout,null);
        final EditText txtun = (EditText) dialog_layout.findViewById(R.id.txtusername);
        final EditText txtps = (EditText) dialog_layout.findViewById(R.id.txtuserpass);
        builder.setView(dialog_layout)

                .setPositiveButton("LogIn", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        String uname =txtun.getText().toString();
                        String pass = txtps.getText().toString();

                        if (uname.equals("Yasir Ameen") && pass.equals("admin123@")) {

                            Toast.makeText(MainActivity.this, "Login Success", Toast.LENGTH_SHORT).show();
                            dialogInterface.dismiss();
                        }else {
                            Toast.makeText(MainActivity.this, "Login Failed", Toast.LENGTH_SHORT).show();

                        }


                    }
                })
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });

        AlertDialog dialog = builder.create();
        dialog.show();


    }
});

custom dialo

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

3 Comments

Leave a Comment