Custom Dialog and Custom AlertDialog Box in Android

In today’s android tutorial, we are going to learn how to create both custom dialog and custom AlertDialog box in android. Before we dive into the tutorial and start coding, it is important we understand what is android dialog and what it is use for.

Android dialog is like a pop-up window that is use to draw users attention to some important information and or to perform an action before they continue with what they are doing. We will start this tutorial with the custom android dialog and thereafter we will move ahead to demonstrate how to create a custom AlertDialog box in android.

In android, dialog class is the base class of other dialogs like AlertDialog, ProgressDialog, DatePickerDialog or TimePickerDialog. We have an extensive and well detailed tutorial on ProgressDialog. You can take time and read the tutorial. We are going to cover the DatePickerDialog and TimePickerDialog in our subsequent tutorials so I will suggest you subscribe to be among the first to be notified once the tutorials are published.

Android does not have a default dialog layout, to create a simple dialog box, we will need to create a layout for the dialog and use the layout to set the dialog’s content view. Furthermore, we will use the instance of the dialog to set all the information we need.

Before we start, the first thing I will do is to list the environment and tools I will use in this tutorial but you are free to use whatever environment you are familiar with.

Windows Vista

Eclipse (ADT)

Samsung Galaxy Fame Lite

Min SDK 8

Target SDK 19

There is no better time to start creating our application than now. To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: CustomDialog

Package: com.inducesmile.customdialog

Keep other default selections.

Continue to click on next button until Finish button is active

Then click on Finish Button

If you can’t follow the steps above, you can also follow it visually below. The dialog below shows the detail information for new android project creation.

custom1

After you have done with the project information, click on the next button. On the next dialog box that will appear as shown below, make sure that the activity checkbox is checked. Click the next button

custom2

On the next dialog box, you will be instructed to enter the name of the activity to be created. You can just leave the MainActivity that has been pre-filled and click the finish button.

custom3

If everything went well for you, your IDE will create a new android project. If you are using Eclipse IDE for this project as I do, your new project structure will look similar to this.

custom4

Custom Dialog

In our custom dialog example, we are going to create a button in our MainActivity.java file. When the button is click, a custom dialog will appear. We will also create a new layout for our custom dialog. So we will start with our activity_main.xml file. Double click on this file located in the layout folder to open it in your IDE. You can use the code or design view to create a new button view control. In the design view, drag and drop a button view on the layout file. You can also copy and paste the following code in your layout file to get you going.

<RelativeLayout 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="com.inducesmile.customdialog.MainActivity" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="109dp"
        android:contentDescription="@string/app_name"
        android:text="@string/button_name" />
</RelativeLayout>

Open strings.xml file located in your project values folder and copy and paste this line of code.

<string name="button_name">Open Dialog</string>
<string name="close_dialog_button">Close Dialog</string>
<string name="text_dialog">The text content of this dialog is used for experiment so it might be make any meaning to you</string>

To create the custom layout for our dialog, right click on your layout folder > click on New > click on others > click on android xml android file > click on Next button > enter the xml layout file name as customdialog_layout > select RelativeLayout in the option box > click finish.

In the customdialog_layout file you created, copy and paste the following code. You have the freedom to experiment with different type of view that you will like to see on your custom dialog. In this example, we are going to use a TextView, ImageView and Button as shown in the code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ImageView
        android:id="@+id/dialog_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="34dp"
        android:layout_marginTop="45dp"
        android:contentDescription="@string/app_name"
        android:src="@drawable/abc_ab_bottom_solid_dark_holo" />
    <TextView
        android:id="@+id/dialog_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/dialog_image"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/dialog_image"
        android:text="@string/text_dialog" />
    <Button
        android:id="@+id/dialog_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/dialog_text"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="@string/close_dialog_button" />
</RelativeLayout>

Now we will move to the MainActivity.java file. We will create an instance of our button view control and attach an event listener to it so that whenever it is click we let it open the Custom dialog box. The code for the MainActivity.java file is shown below. Don’t worry I will explain what we have done in the code.

package com.inducesmile.customdialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
   private Context context = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button openDialogButton = (Button)findViewById(R.id.dialog_button);
        openDialogButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
           final Dialog openDialog = new Dialog(context);
           openDialog.setContentView(R.layout.customdialog_layout);
           openDialog.setTitle("Custom Dialog Box");
           TextView dialogTextContent = (TextView)openDialog.findViewById(R.id.dialog_text);
           ImageView dialogImage = (ImageView)openDialog.findViewById(R.id.dialog_image);
           Button dialogCloseButton = (Button)openDialog.findViewById(R.id.dialog_button);
           dialogCloseButton.setOnClickListener(new OnClickListener(){
              @Override
              public void onClick(View v) {
               // TODO Auto-generated method stub
                  openDialog.dismiss();
              }                                                                             
         });
         openDialog.show();
      }
   });
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.main, menu);
      return true;
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
   // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
        return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

 

What we have done so far is the set the customdialog_layout to our dialog object. We used the Dialog object to get the instances of our view controls e.g. Button dialogCloseButton = (Button)openDialog.findViewById(R.id.dialog_button); Finally, we show the Dialog when we click on the button present in our MainActivity.java file and close the Dialog when the close button on the Dialog is clicked.

dialog

Moving Ahead

We will move on to explore how we can use the AlertDialog in android application. As we learned before, the AlertDialog is a subclass of the dialog. It is also important to know that the AlertDialog class in android has a default dialog that we can use. We will demonstrate how to use the default AlertDialog and subsequently learn how we can make a custom AlertDialog.

Default AlertDialog

In other to create a new default AlertDialog, we can easily create an instance of AlertDialogBuilder. The AlertDialogBuilder is an inner class of the AlertDialog. An object of this class can be create with this one line of code below

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

With the object of the AlertDialogBuilder, the AlertDialog can be customized with different methods and properties present in this class.

We will create a new android project called DefaultAlertDialog. Follow the initial step we used to create the first project and also add a button view control to the MainActivity.java file in the project. The activity_main.xml code will look the same like the first project. You can copy it and paste as shown below

<RelativeLayout 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="com.inducesmile.customdialog.MainActivity" >

    <Button
        android:id="@+id/dialog_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="109dp"
        android:contentDescription="@string/app_name"
        android:text="@string/button_name" />
</RelativeLayout>

The code for the MainActivity.java is shown below. In the OnClick callback method of the activity class, we have created a default AlertDialog box using the AlertDialogBuilder.

package com.inducesmile.defaultalertdialog;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {
   private Context context = this;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Button openDialogButton = (Button)findViewById(R.id.dialog_button);
      openDialogButton.setOnClickListener(new OnClickListener(){

      @Override
      public void onClick(View arg0) {
         AlertDialog.Builder builder = new AlertDialog.Builder(context);
         builder.setTitle("Default AlertDialog Tutorial");
         builder.setMessage("Check out how Default AlertDialog looks in Android");
         builder.setNegativeButton("Close Dialog", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
           // TODO Auto-generated method stub
           dialog.dismiss();
       }
    });
     AlertDialog alertDialog = builder.create();
     alertDialog.show();
   }
  });
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
 }
 @Override
  public boolean onOptionsItemSelected(MenuItem item) {
     // Handle action bar item clicks here. The action bar will
     // automatically handle clicks on the Home/Up button, so long
     // as you specify a parent activity in AndroidManifest.xml.
     int id = item.getItemId();
     if (id == R.id.action_settings) {
        return true;
     }
     return super.onOptionsItemSelected(item);
    }
}

You can see from the image below that the default AlertDialog box has the default android theme. It is not bad but what if you want to make a custom look and feel for our AlertDialog box? I heard you ask if it is possible. Yes it is. That is what we will cover before the end of this tutorial.

Custom AlertDialog Box

We will follow the same process we used when we created a custom dialog box in the beginning. First thing to do is to create a new android project. We have gone through this process several times so I know by now you can do it. You can also reference the first part if you have forgotten anything. We will name our new android project CustomAlertDialog.

Once you are done with the new project, go to the layout folder and create a new file called customalertdialog_layout. This file is to be used for our custom AlertDialog. You can copy and paste the code below to this file. We are creating an EditText view control and we will instruct our users to enter their names. Once they entered their name and click on the submit button, the entered name will appear on the MainActiviy.java file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/text_instruction"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp"
        android:text="@string/alert_info" />
    <EditText
        android:id="@+id/user_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_instruction"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:inputType="text"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:ems="10" >
        <requestFocus />
    </EditText>
</RelativeLayout>

You can see that we have two view controls. The TextView is used to notify the user what to do while the EditText is used to accept input from the users.

Now, double click on the MainActivity.java file and copy and paste the code below to the file.

package com.inducesmile.customalertdialog;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
     private Context context = this;
     private TextView textFromDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textFromDialog = (TextView)findViewById(R.id.text_from_dialog);
        Button openDialogButton = (Button)findViewById(R.id.dialog_button);
        openDialogButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View view) {
           LayoutInflater inflater = LayoutInflater.from(context);
           View dialogLayout = inflater.inflate(R.layout.customalertdialog_layout, null);
           AlertDialog.Builder builder = new AlertDialog.Builder(context);
           builder.setView(dialogLayout);
           TextView indtruction = (TextView)dialogLayout.findViewById(R.id.text_instruction);
           final EditText userInput = (EditText)dialogLayout.findViewById(R.id.user_input);
           builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

           @Override
           public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
               dialog.dismiss();
           }
        });
        builder.setPositiveButton("Submit Name", new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
          String userInputContent = userInput.getText().toString();
          if(userInputContent.equals("")){
             Toast.makeText(context, "You must enter a name in the field", Toast.LENGTH_LONG).show();
             return;
         }
         textFromDialog.setText(userInputContent);
      }
      });
      AlertDialog customAlertDialog = builder.create();
      customAlertDialog.show();
     }             
   });
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.main, menu);
     return true;
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
     // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
       int id = item.getItemId();
       if (id == R.id.action_settings) {
          return true;
       }
       return super.onOptionsItemSelected(item);
    }
}

What we have done in the code above is when the open dialog button is clicked, it will open our custom AlertDialog with our new layout attached to it. We accomplish this by inflating our layout and setting it as our custom AlertDialog view.

If a user clicks on Cancel button in on AlertDialog the dialog will close. On the other if a user enters a name and click the submit button, the text will be displayed on the TextView control in the MainActivity.java file.

This brings us to the end of this tutorial. If there is something I did not explain well and you wanted more light on it, just drop a message in the comment section.

You can download all the codes for this tutorial below. If you are having hard time downloading the tutorials, you can drop your email address and I will forward it to your inbox.

 

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published.

No Responses

Add a Comment