Dialog in Android

It is a small window that appears before the activity and then the activity loses attention and the Dialog gains all user focus. They are of different types:

1)Alert Dialog

2)Progress Dialog

3)Date picker

4)Time Picker

In this article I would like to discuss about Alert Dialog.

Dialog is the base class for creating dialogs. We usually use its subclasses for creating dialog depending on the type of dialogs we use in our applications.

The subclass we use for creating alert dialog is AlertDialog.

First of all we need to create a Builder object of the class AlertDialog.Builder.

Here it is,

AlertDialog.Builder builder1=new AlertDialog.Builder(MyAlertdialogActivity.this);

where MyAlertDialogActivity is my activity here.

Next is setting the message for your dialog.

Here,
builder1.setMessage("Please Press Ok");

Now, I’ll jot down the code for alert dialog with one button. We use the method setNeutralButton() for that as shown below.

builder1.setNeutralButton("OK",new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
  Toast.makeText(getApplicationContext(), "Ok is pressed", Toast.LENGTH_LONG).show();
  }
  });

Here, DialogInterface in the code is used to allow some code to be run when an item on the dialog is clicked. Here I’ve given a Toast which says ‘Ok is pressed’ when the neutral button ‘OK’ is clicked.

Hope this made everything in the code so far clear.

Finally, we need to create the Alert Dialog with the features defined(ie,the message,the button ,Toast message etc) and display the same. So, the code for that is

builder1.show();

The code written together looks like this:

btnalert1.setOnClickListener(new OnClickListener() {  @Override  public void onClick(View v) {
// TODO Auto-generated method stub  AlertDialog.Builder builder1=new AlertDialog.Builder(MyAlertdialogActivity.this);
builder1.setMessage("Please Press Ok");  builder1.setNeutralButton("OK",new DialogInterface.OnClickListener() {  @Override  public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub  Toast.makeText(getApplicationContext(), "Ok is pressed", Toast.LENGTH_LONG).show();
 }  });  builder1.show();  }  });

where btnalert1 is the Button which on clicking displays the alert dialog.

And the output looks like this:

When Ok is clicked the screen looks like this:

We can also create Alert Dialog with Buttons side-by-side. Here is the code,

  AlertDialog.Builder builder2=new AlertDialog.Builder(MyAlertdialogActivity.this);
  builder2.setMessage("Press OK or Cancel");
  builder2.setPositiveButton("OK",new DialogInterface.OnClickListener() {

  @Override
public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub

  Toast.makeText(getApplicationContext(), "U Clicked OK", Toast.LENGTH_LONG).show();

  }

  });

  builder2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

@Override
  
public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub

  Toast.makeText(getApplicationContext(), "U Clicked Cancel ", Toast.LENGTH_LONG).show();

  }

  });

  builder2.show();

This is how the output looks:

When the OK button is clicked:

Now just check how we can create an Alert Dialog with a list of choices. The code for the same is

final CharSequence[] items={"One","two","three"};

  btnalertlist.setOnClickListener(new OnClickListener() {

  @Override

  public void onClick(View v) {

// TODO Auto-generated method stub
  
AlertDialog.Builder builder3=new AlertDialog.Builder(MyAlertdialogActivity.this);
  builder3.setTitle("Pick your choice").setItems(items, new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub
  
Toast.makeText(getApplicationContext(), "U clicked "+items[which], Toast.LENGTH_LONG).show();
  
}
  
});

  builder3.show();

  }

  });

This is how the output for this looks:

When one is chosen, the screen looks like this:

The whole code is given below:

package com.deepthi.alertdialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MyAlertdialogActivity extends Activity {
/** Called when the activity is first created. */
Button btnalert1,btnalert2,btnalertlist;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnalert1=(Button)findViewById(R.id.btndialog1);
btnalert1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder builder1=new AlertDialog.Builder(MyAlertdialogActivity.this);
builder1.setMessage("Please Press Ok");
builder1.setNeutralButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Ok is pressed", Toast.LENGTH_LONG).show();
}
});
builder1.show();
}
});
btnalert2=(Button)findViewById(R.id.btndialog2);
btnalert2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder builder2=new AlertDialog.Builder(MyAlertdialogActivity.this);
builder2.setMessage("Press OK or Cancel");
builder2.setPositiveButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "U Clicked OK", Toast.LENGTH_LONG).show();
}
});
builder2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "U Clicked Cancel ", Toast.LENGTH_LONG).show();
}
});
builder2.show();
}
});
btnalertlist=(Button)findViewById(R.id.btndialog3);
final CharSequence[] items={"One","two","three"};
btnalertlist.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder builder3=new AlertDialog.Builder(MyAlertdialogActivity.this);
builder3.setTitle("Pick your choice").setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "U clicked "+items[which], Toast.LENGTH_LONG).show();
}
});
builder3.show();
}
});
}
}

I’m planning to post articles regarding Progress Dialog, Date Picker and Time Picker also.So keep reading and also share your experiences working with android.

Advertisements

, , , , , , ,

  1. #1 by coral reef restaurant at epcot on February 25, 2012 - 7:26 pm

    Awesome post, keep up the great posts!

    • #2 by Deepthi G on February 25, 2012 - 7:57 pm

      hey
      Thanks for your appreciation..

  2. #3 by Marion Pilch on March 10, 2012 - 4:46 pm

    Great post, I conceive website owners should learn a lot from this weblog its real user friendly. So much excellent info on here :D.

  3. #4 by Rakesh reddy on December 4, 2012 - 6:03 pm

    ur blog is so good, thank u

  4. #5 by Mainak on October 2, 2013 - 9:48 am

    please tell me how to use my custom layout button? and no need alert setNegativeButton and setPositiveButton.
    i send my layout—-
    —————————————————

    <Button
    android:id="@+id/mbutton1"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="50dp"
    android:text="@string/btnMod1"
    android:textColor=”@color/black” />

    <Button
    android:id="@+id/mbutton2"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="40dp"
    android:text="@string/btnMod2"
    android:textColor=”@color/black” />

  5. #6 by Quakig on May 13, 2014 - 8:00 pm

    When you are putting all this effort into writing a blog, I think you should spend some time in formatting code to make it more readable and perhaps you should use some code highlighting plugin.

    Just a thought. Thanks anyways !

  6. #8 by Kaushal on January 14, 2016 - 11:42 am

    How can i use 3 different intents in the builder3 onclick options…..??

  7. #9 by shabeer on May 4, 2016 - 9:00 pm

    Hi,
    Iam shabeer..android programmer beginner…..

    Your post is good..i want alert dialog to show list..no need of selection..but ok cancel button should b there,…used your code…but item not displaying

  8. #10 by shabeer on May 4, 2016 - 9:01 pm

    AlertDialog.Builder builder2=new AlertDialog.Builder(((AppCompatActivity) getActivity()));
    builder2.setMessage(“Proirity Overlooking Not allowed..Assigning jobs .Press OK or Cancel”);
    final CharSequence[] items={“One”,”two”,”three”};

    builder2.setItems(items, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

    Toast.makeText(((AppCompatActivity) getActivity()), “dont know”, Toast.LENGTH_LONG).show();
    }
    });
    builder2.setPositiveButton(“OK”, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

    Toast.makeText(((AppCompatActivity) getActivity()), “U Clicked OK”, Toast.LENGTH_LONG).show();
    // paasing an object => EventBus.getDefault().postSticky(selectedConsumerList);
    //passing a list is differ from an object
    EventBus.getDefault().postSticky(gson.toJson(selectedConsumerList));
    Fragment fragment = new JobAssaignFragment();
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(“back_frag”).commit();

    }

    });

    builder2.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    Toast.makeText(((AppCompatActivity) getActivity()), “U Clicked Cancel “, Toast.LENGTH_LONG).show();

    }

    });

    builder2.show();

  9. #11 by vishwajay on February 27, 2017 - 10:59 am

    Is there a way to apply this using a string-array list so that we’re not locked in the code to a singular language? I’m unaware of a way to load a string-array into a character sequence statically, as you have done, but is there another way to do this so that it works?

  1. thank you :D

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: