Jump to content




Recent Status Updates

  • Photo
      30 Sep
    rhossis

    laptop hard disk seated beneath motherboard but with no access panel. 7 hours to replace :(

    Show comments (3)
  • Photo
      19 Sep
    Chall

    I love it when you go to write a help thread, then while writing, you reach an enlightenment, and figure it out yourself.

    Show comments (3)
View All Updates

Developed by Kemal Taskin
Photo
* * * * * 1 votes

AlertDialog Tutorial


  • Please log in to reply
2 replies to this topic

#1 Rakso

Rakso

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 329 posts
  • Programming Language:Java
  • Learning:Java, C++

Posted 30 December 2011 - 12:11 PM

What is a dialog?
A dialog is often a small window that pops up infront of the current activity that is running, When the dialog is called the activity that is under the dialog loses focus and the dialog allows the user to interact with it. The point of the dialogs is to interupt the user and do a small tasks related to the application that is in progress.

But what is the AlertDialog?
An AlertDialog i find very usefull because it can be used for so many things, It can hold from 0 - 3 buttons and you can design it as a list with selectable items, It can also use Check boxes and Radio buttons so its not only the normal buttons and this means we can use it for alot of things.
With the AlertDialog you can make realy cool things if you think out of the box, Some small things is like when the user want to exit the application you could create a AlertDialog saying "Do you really want to exit?" and if could be two buttons like "Yes" and "No".

When should i choose to use this dialog?
Anytime your dialog needs something of the following:
Title
Text message
1-3 buttons
List with selectable items(CheckBoxes, RadioButtons can be used here but its not required)

How do we code an AlertDialog?
First we can start with making a dialog with the buttons next to eachother, Lets say an AlertDialog that asks if we want to quit the application or not.

First we make a AlertDialog builder that we will use to build our AlerDialog:
AlertDialog.Builder builder = new AlertDialog.Builder(this);

Then we can use this builder to set up our AlertDialog however we want it:
builder.setMessage("Do you really want to quit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.onclickListener() {
           public void onclick(DialogInterface dialog, int id) {
                MyActivity.this.finish();
           }
           })
       .setNegativeButton("No", new DialogInterface.onclickListener() {
           public void onclick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
           });

A small notice to this part where we set up the Dialog, We don't add a ";" before the end because we want to create all the settings in one command (One big command) but its good to do it this way.
In this code above we first set a message for the Dialog that will be displayed, Then we make sure the user can cancel this message.
We create a positive button that has the text "Yes" and inside the onclick method we write the code that we want to happend when this button was pressed and in this case we tell the activity that is running in the background to stop / close.
And then we do the same with negative button but instead of quiting the activity we just close the dialog.

Then simply to show this dialog we put this peace of code:
AlertDialog alert = builder.create();
//The above line didn't show the dialog i added this line:
alert.show();

When this line of code above gets called the dialog we created with the builder will get called and shown on the screen, It would look something like this:
alertdialog_example.png

Now lets make a list instead!
To make a list with items instead we use a method called setItems()
final CharSequence[] items = {"1", "2", "3"};
 
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a number");
builder.setItems(items, new DialogInterface.onclickListener() {
    public void onclick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();
//The above line didn't show the dialog i added this line:
alert.show();

As you can see here we first make a CharSequence array which holds 3 different values, In this example they just hold 1, 2 and 3.
In this example we also use something we didn't se before, builder.setTitle("Title"); You can use this setTitle if you have the buttons we used in the previous example too if you want.
But then we do something else that is new.. setItems as i mentioned above. In the first parameter we put our CharSquence array which is our items and with this we create an DialogInterface.onclickListener which we also used before to get the onclick method. Inside the onclick we make a Toast Notification, This Toast uses the item integer which is inside the onclick methods parameters and this gets a number from 0-2 if im correct and the 0 represents the "1" in our array and 1 represents "2" in our array and 2 represents "3".. And then with the Toast print out the CharSequence of the item we pressed.
Example:
If i would press the button 1 in the list the toast would print out 1 and if i pressed 2 it will print 2 and same with 3.

Here is a picture how this Dialog should look like:
pickanumber.png

And when i pressed numer 2 of the buttons it should look like this:
afternumberpicked.png

How do i do if i want Radio Buttons or Check Boxes?
You would have to use the two methods: setMultiChoiceItems() for CheckBoxes (Which i wont explain today) and setSingleChoiceItems() for RadioButtons.

I will show you how both looks, First if we would make the RadioButtons all we would have to change is this line of code in the one we had for our previous list:
builder.setSingleChoiceItems(items, -1, new DialogInterface.onclickListener() {
Notice that we do not only change it to setSingleChoiseItems we also add a -1 after items.. And this is just to tell the Dialog that we want no RadioButton checked when the Dialog is brought up.

Here is whole code if you want to use RadioButtons:
final CharSequence[] items = {"Red", "Green", "Blue"};
 
AlertDialog.Builder builder = new AlertDialog.Builder(this);
04
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, -1, new DialogInterface.onclickListener() {
    public void onclick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();
//And if the line above didn't bring ur dialog up use this bellow also:
alert.show();


Here is a picture how it would look like:
picknumberwithradiobutton.png

Edited by TheCompBoy, 05 January 2012 - 09:08 AM.

  • 0
Was my post useful? Please take your time and press the Like This button below my post, Big Thanks!

#2 Alexander

Alexander

    YOL9

  • Moderator
  • 3,925 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 30 December 2011 - 02:30 PM

Very nice tutorial, I was always considering buying an Android just to tinker with mobile applications - they make it so simple.
  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#3 Rakso

Rakso

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 329 posts
  • Programming Language:Java
  • Learning:Java, C++

Posted 31 December 2011 - 03:33 AM

I made some Android applications myself just for fun, So i thought i could share what i've learned..
Theese tutorials im posting here are directly from my blogg.
  • 0
Was my post useful? Please take your time and press the Like This button below my post, Big Thanks!