Androd Dialogs

When developing an app, one of the basic ways to show a user something important is through a dialog. 


A dialog is a small popup message with one or two buttons to show the user an important message or to ask the user for some input.

There are various ways to generate a simple dialog. I will be showing four general purpose dialogs that I have used the most.

Simple Dialog, Date picker, Time Picker and using my own layout in a dialog.

Let's create a sample project.

From the previous articles we have borrowed the "button_background.xml" file in the drawable folder.

drawable/button_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
 
  <!-- disabled -->
  <item android:state_enabled="false" >
       <shape android:shape="rectangle">
            <gradient
                   android:startColor="#454545"
                android:endColor="#454545"
                   android:angle="-90"
                   android:type="linear"
                   />
               <corners android:radius="5dp" />
        </shape>
    </item>
 
 <!-- pressed -->
  <item android:state_pressed="true" android:state_enabled="true" >
       <shape android:shape="rectangle">
            <gradient
                   android:startColor="#64334C"
                android:endColor="#300019"
                   android:angle="-90"
                   android:type="linear"
                   />
               <corners android:radius="5dp" />
        </shape>
    </item>
 
  <!-- focused -->
  <item android:state_focused="true">
      <shape android:shape="rectangle">
            <gradient
                   android:startColor="#C76699"
                android:endColor="#610033"
                   android:angle="-90"
                   android:type="linear"
                   />
               <corners android:radius="5dp" />
               <stroke android:width="2dp" android:color="#dddddd"/>
        </shape>
    </item>
 
      <!-- default -->
    <item>
        <shape android:shape="rectangle">
            <gradient
                   android:startColor="#C76699"
                android:endColor="#610033"
                   android:angle="-90"
                   android:type="linear"
                   />
               <corners android:radius="5dp" />
        </shape>
    </item>
</selector>


Now open the activity_main.xml file and add four buttons to it. These buttons will be used to show dialogs.

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/simpleDialogButton"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:text="Simple Dialog"
        android:background="@drawable/button_background"
        android:textColor="#ffffff"
        />
    <Button
        android:id="@+id/timeDialogButton"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:text="Time Dialog"
        android:background="@drawable/button_background"
        android:textColor="#ffffff"
        />
    <Button
        android:id="@+id/dateDialogButton"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:text="Date Dialog"
        android:background="@drawable/button_background"
        android:textColor="#ffffff"
        />
    <Button
        android:id="@+id/customDialogButton"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:text="Custom Dialog"
        android:background="@drawable/button_background"
        android:textColor="#ffffff"
        />
</LinearLayout>

For one of our custom layouts create a file custom_dialog_layout.xml in the layout folder.

layout/custom_dialog_layout.xml

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

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Option1" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option2" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option3" />
    </RadioGroup>
    <Button
            android:id="@+id/okButton"
            android:layout_height="wrap_content"
            android:layout_width="100dp"
            android:padding="10dp"
            android:text="Ok"
            />
</LinearLayout>


Now MainActivity.java has all the code you need to make the dialogs, for proper clarification of the syntax please check the comments in the code.

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        /*
         * Add listeners to the buttons and call the appropriate methods
         */

       
        ((Button)findViewById(R.id.simpleDialogButton)).setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createSimpleDialog();
            }
        });
        ((Button)findViewById(R.id.dateDialogButton)).setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createDateDialog();
            }
        });
        ((Button)findViewById(R.id.timeDialogButton)).setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createTimeDialog();
            }
        });
        ((Button)findViewById(R.id.customDialogButton)).setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createCustomDialog();
            }
        });
    }

    /*
     * This is a convenient method to show a toast after dismissing the dialog
     */

    private void showToast(String toastString)
    {
        Toast.makeText(MainActivity.this, toastString, Toast.LENGTH_SHORT).show();
    }
   
    /*
     * This is the basic method to create a dialog
     * This sets a message and two buttons to the dialog
     */

    private void createSimpleDialog()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setMessage("This is simple dialog")
               .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       showToast("Simple dialog Ok button pressed");
                   }
               })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       showToast("Simple dialog Cancel button pressed");
                   }
               });
        builder.create().show();
    }
   
    /*
     * This method used the builtin DatePickerDialog to ask user to select a date
     * We use a Calendar instance to get the current date, we also add a listener(OnDateSetListener) to the dialog to get the selected date 
     */

    private void createDateDialog(){
        Calendar c = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(MainActivity.this, mDateSetListener, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }
   
    /*
     * This listener is called when we select date in the DatePickerDialog
     */

    OnDateSetListener mDateSetListener = new OnDateSetListener() {
       
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            // TODO Auto-generated method stub
           
            showToast("Selected date: "+dayOfMonth+"/"+(monthOfYear+1)+"/"+year);
        }
    };
   

    /*
     * This method used the builtin TimePickerDialog to ask user to select a date
     * We use a Calendar instance to get the current time, we also add a listener(OnTimeSetListener) to the dialog to get the selected time 
     */

    private void createTimeDialog() {
        Calendar c = Calendar.getInstance();
        TimePickerDialog dialog = new TimePickerDialog(MainActivity.this, mTimeSetListener, c.get(Calendar.HOUR), c.get(Calendar.MINUTE), false);
        dialog.show();
    }
   
    /*
     * This listener is called when we select time in the TimePickerDialog
     */

    OnTimeSetListener mTimeSetListener = new OnTimeSetListener() {
       
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // TODO Auto-generated method stub
            showToast("Selected time: "+hourOfDay+":"+minute);
        }
    };
   
    /*
     * This method creates a custom dialog using the layout we has created previously
     */

    private void createCustomDialog(){
        //Create a dialog object
        final Dialog dialog = new Dialog(MainActivity.this);
        //Set its layout
        dialog.setContentView(R.layout.custom_dialog_layout);
        //Set the title
        dialog.setTitle("This is custom layout");
        //Make it cancelable
        dialog.setCancelable(true);
        //We need to dismiss the dialog so we add a listener to the ok button
        dialog.findViewById(R.id.okButton).setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
       
        dialog.show();
    }
}

This is the the very basic code to make an interesting UI. We can always use the custom dialogs to create a very user interactive app but don't overdo it or it may end up being too much of a hassle for the user.

Screenshots:

Article5Img1.png   Article5Img2.png

Article5Img3.png  Article5Img4.png

Up Next
    Ebook Download
    View all
    Learn
    View all