ATTENTION ATTENTION
gear.huuah.com has launched. Visit the shop at http://gear.huuah.com/. Lots of Photo Gear at the moment
ATTENTION ATTENTION
Itsplanned.com is just launched! - Task and project management made easy. Try it for free.

Create your own lists of things to do - arrange the order to do them - move them around - group them

No limitations - all free project management - try the free demo before signing up - demo: itsplanned.com
Dialog boxes in Android
02.04.2010

Dialog boxes

Showing dialog boxes from an android application can be usefull.

This article will be using a layout like this – 4 buttons with their own function (complete code id listed last in this article):
Android Dialog Layout

Info boxes

An info box is called a Toast on the Android OS. A toast message is a small window that appear in the button half on the device screen. It should only be used as an information service to the user. The window disappears by itself, so as a developer you can not be sure that the user actually sees the message displayed. If you want to user to take action on the popup window, you should use an alert dialog instead – this is covered later on.

The Toast message is very easy to create. The most simple way to display a toast is by calling the maketext()-method like this:

...
Toast.makeText(this, "This is the Toast message", Toast.LENGTH_LONG).show();
...

This will display a box like this:
Android Toast

Alert boxes

The Alert box should be use when you want to make sure, that the user reads and takes action on the information window. To display the alert window, can be done like this:

...
            // prepare the alert box                   
            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            
            // set the message to display
            alertbox.setMessage("This is the alertbox!");
            
            // add a neutral button to the alert box and assign a click listener
            alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                
                // click listener on the alert box
                public void onClick(DialogInterface arg0, int arg1) {
                    // the button was clicked
                    Toast.makeText(getApplicationContext(), "OK button clicked", Toast.LENGTH_LONG).show();
                }
            });
            
            // show it
            alertbox.show();
...

This will popup a window like this:
Android Alertbox

When is OK button is clicked, it will – in this example – show a toast message like this:
Android OK toast

Yes/no boxes

If one button on the alert dialog isn’t enough we can use the setPositiveButton() and setNegativeButton() on the AlertDialog Builder like this:

...
            // prepare the alert box                   
            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            
            // set the message to display
            alertbox.setMessage("This is the alertbox!");
                    
            // set a positive/yes button and create a listener                    
            alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                
                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(getApplicationContext(), "'Yes' button clicked", Toast.LENGTH_SHORT).show();
                }
            });
            
            // set a negative/no button and create a listener 
            alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

                // do something when the button is clicked                
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
                }
            });
            
            // display box
            alertbox.show();
...

This will show a window like this:
Android Yes/No window

When either of the buttons is clicked it will run the assigned listener. Here we have clicked the yes button:
Android Yes toast

Loading box

If you want to display a loading window or some kind of progress alert it can be done with the ProgressDialog like this:

...
            // prepare the dialog box
            ProgressDialog dialog = new ProgressDialog(this);
            
            // make the progress bar cancelable
            dialog.setCancelable(true);
            
            // set a message text
            dialog.setMessage("Loading...");
            
            // show it
            dialog.show();
...

This will popup a progress window like this:
Android Progress Window

This window will not close by itself. You have to make it complete, by running a code that increment the internal counter on the ProgressDialog, so that the progressdialog can calculate the percentage by itself. For this we should use a thread-based application, that runs some code in the background and from there set the progress bar at the given value. This is not covered in this article though.


Complete code

The small code samples above are shown here in the complete formation, including the main.xml layout.

main.xml

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

<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" android:id="@+id/toastbtn"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Alert" android:id="@+id/alertbtn"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Yes/No" android:id="@+id/yesnobtn"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Progress" android:id="@+id/progressbtn"></Button>
</LinearLayout>

dialogboxes.java

package huuah.dialogboxes;

import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.app.ProgressDialog;

public class dialogboxes extends Activity implements OnClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // set a click listener on the toast button
        Button toast = (Button) findViewById(R.id.toastbtn);
        toast.setOnClickListener(this);
            
        // set a click listener on the alert button
        Button alert = (Button) findViewById(R.id.alertbtn);
        alert.setOnClickListener(this);
        
        // set a click listener on the yesno button
        Button yesno = (Button) findViewById(R.id.yesnobtn);
        yesno.setOnClickListener(this);
        
        // set a click listener on the progress button
        Button progress = (Button) findViewById(R.id.progressbtn);
        progress.setOnClickListener(this);        
    }
    
       
    public void onClick(View view) {
        // which button is clicked?
        
        // the Toast button
        if (view == findViewById(R.id.toastbtn)) {
            // display the toast popup window
            Toast.makeText(this, "This is the Toast message", Toast.LENGTH_LONG).show();
        }

        // the Alert button the activated
        if (view == findViewById(R.id.alertbtn)) {
        
            // prepare the alert box                   
            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            
            // set the message to display
            alertbox.setMessage("This is the alertbox!");
            
            // add a neutral button to the alert box and assign a click listener
            alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                
                // click listener on the alert box
                public void onClick(DialogInterface arg0, int arg1) {
                    // the button was clicked
                    Toast.makeText(getApplicationContext(), "OK button clicked", Toast.LENGTH_LONG).show();
                }
            });
            
            // show it
            alertbox.show();
        }
        
        // the yesno button is clicked
        if (view == findViewById(R.id.yesnobtn)) {        
            // prepare the alert box                   
            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            
            // set the message to display
            alertbox.setMessage("This is the alertbox!");
                    
            // set a positive/yes button and create a listener                    
            alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                
                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(getApplicationContext(), "'Yes' button clicked", Toast.LENGTH_SHORT).show();
                }
            });
            
            // set a negative/no button and create a listener 
            alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

                // do something when the button is clicked                
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
                }
            });
            
            // display box
            alertbox.show();
        }
 
        // progress button clicked
        if (view == findViewById(R.id.progressbtn)) {
            // prepare the dialog box
            ProgressDialog dialog = new ProgressDialog(this);
            
            // make the progress bar cancelable
            dialog.setCancelable(true);
            
            // set a message text
            dialog.setMessage("Loading...");
            
            // show it
            dialog.show();
        }
        
    }
}

I hope this will the useful. If you want to read more on this subject, then take a look at some of the Android books out there

20 Responses to “Dialog boxes in Android”

  1. Ruwan Says:

    thanks man , this helped !!!

  2. zire Says:

    Thank you very much for those samples.
    I search for a while and this is the best and simplest .

  3. Arshad Says:

    Thanks a lot man,Very nice examples with codes.
    Peace.

  4. rosebeat Says:

    I get an error message as
    Application has stopped unexpectedly and I have to force close it.
    Why is that????

  5. David Carral Says:

    Thanks a lot, very very nice, easy, simple & good examples, you saved my ass!!

  6. Afonso Lage Says:

    Man,

    I’m so glad with this post. Very nice example and this SS help us a lot.

    Thx agin.

    Att,

    Afonso Lage.

  7. Priyanka Says:

    Thanks..
    Very good and helpful..
    :)

  8. Rob Says:

    Fantastic examples, straight to the point, just what i needed to implement a alert dialog with ok button. The toast example is very helpful too :)

  9. Malagas Says:

    This is just excellent. I’ve tried some examples of dialogs and button events but they didn’t work well. This works fine!!! Thanks for your example.

  10. Malagas Says:

    Now watch the results:

    Here is a custom dialog, from a XML file layout ;)

    The main.xml:

    Now the costum_dialog.xml : (English error :S)

    and strings.xml:

    CustomDialogEx App!
    Custom_Dialog_Ex

    finally CustomDialogEx.java :

    package com.example.custom_diag;

    import android.app.Activity;
    import android.app.Dialog;
    import android.os.Bundle;
    import android.view.View.OnClickListener;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.app.ProgressDialog;

    public class CustomDialogEx extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    static final int CUSTOM_DIAG = 10;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /*
    Context mContext = getApplicationContext();
    Dialog dialog = new Dialog(mContext);
    dialog.setOwnerActivity(this);
    dialog.setContentView(R.layout.costum_dialog);
    dialog.setTitle(“Custom Dialog”);

    TextView text = (TextView) dialog.findViewById(R.id.text);
    text.setText(“Hello, this is a custom dialog!”);
    ImageView image = (ImageView) dialog.findViewById(R.id.image);
    image.setImageResource(R.drawable.icon);
    */

    Button btn_diag = (Button) findViewById(R.id.button1);
    btn_diag.setOnClickListener(this);
    /*
    btn_diag.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(), “Bosta”, Toast.LENGTH_SHORT).show();

    //showDialog(CUSTOM_DIAG);
    }
    });
    */
    // dialog.show();
    }

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v == findViewById( R.id.button1))
    {
    //Context mContext = getApplicationContext();
    Dialog dialog = new Dialog(this);
    //dialog.setOwnerActivity(this);

    dialog.setContentView(R.layout.costum_dialog);
    dialog.setTitle(“Custom Dialog”);

    TextView text = (TextView) dialog.findViewById(R.id.text);
    text.setText(“Hello, this is a custom dialog!”);
    ImageView image = (ImageView) dialog.findViewById(R.id.image);
    image.setImageResource(R.drawable.icon);

    dialog.show();

    }
    }

    /*
    @Override
    protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
    switch (id) {
    case CUSTOM_DIAG:

    Toast.makeText(getApplicationContext(), “Bosta”, Toast.LENGTH_LONG).show();

    break;

    default:
    break;
    }

    return super.onCreateDialog(id);
    }
    */

    }

  11. Android Custom Dialog Example | Malagas Home Says:

    [...] event OnClick from a Button, here’s an example that i have made with the major help from this DialogBox [...]

  12. Android Says:

    nice, but if you like to see AlertDialog alone in detail means see http://android-codes-examples.blogspot.com/2011/03/how-to-display-alertdialog-and.html

  13. Satish Says:

    Very nice dude! Very helpful for learners. Keep it up!

  14. Akshay Says:

    Hi Huuha,
    Its a nice tutorial.Again i got help from your example.Thanks plz continue writing……….

  15. Roche Says:

    Thank you for this example. Hope you continue writing useful examples for android developers. More power to you.

  16. dixit Says:

    Hello great work
    really nice tutorial….

  17. Andrew Says:

    Great stuff, I’ve been going insane trying to figure alertboxes out and this tut has answered all of my questions! Easily the best alertbox example out there, thank you very much!!!

  18. Android Custom Dialog Example | Malagas Dev Says:

    [...] a Button, here’s an example of a Custom Dialog that i have made with the major help from this DialogBox [...]

  19. TheRaaaZ Says:

    Thanks man…! I was searching for Alert Dialog and Api Demos were not working for me.. Android Developers guide was also complicated for me but your simple and clean explanation worked for me. Thanks once again

  20. hari Says:

    thanks my dear friend that good example.

Leave a Reply