Tuesday, June 14, 2011

Displaying an Android Pop Up Dialog (AlertDialog) Part Two

In this tutorial we revisit Android Alert Dialogs use as pop up windows and dive into some more advanced features. These include setting positive,negative, and neutral buttons, adding a text view, and setting a completely custom layout.

Intro

In this tutorial we will demonstrate some more advanced features of the Pop Up dialog. These advanced features can be useful, but it is important to reiterate a word of caution. Pop up windows can be annoying.

It can be tempting to throw in a couple of settings in a pop up window, which can be fine, but plan ahead if you want to add more settings in the future. Pop up windows are smaller than a full activity, and can be difficult to deal with if they are presenting too much information.

We are going to build off the code that we created in the first part of the tutorial, Displaying an Android Pop Up Dialog (AlertDialog).

Screenshot showing the positive, negative, and neutral buttons.


Three Buttons

When you use an AlertDialog you get the option of setting names and listeners for up to three buttons. If you don't set a listener for any buttons, the user can dismiss your dialog by pressing the back button.

You can make the text of the buttons say whatever you want.

The code to display the Pop Up is listed below.

private void showPopUp2() {

 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
 helpBuilder.setTitle("Pop Up");
 helpBuilder.setMessage("This is a Simple Pop Up");
 helpBuilder.setPositiveButton("Positive",
   new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {
     // Do nothing but close the dialog
    }
   });

 helpBuilder.setNegativeButton("Negative", new DialogInterface.OnClickListener() {

  @Override
  public void onClick(DialogInterface dialog, int which) {
   // Do nothing
  }
 });
 
 helpBuilder.setNeutralButton("Neutral", new DialogInterface.OnClickListener() {

  @Override
  public void onClick(DialogInterface dialog, int which) {
   // Do nothing
  }
 });

 // Remember, create doesn't show the dialog
 AlertDialog helpDialog = helpBuilder.create();
 helpDialog.show();

}

To show this new Pop Up, simply change the OnClick listener for the showPopUp button to call this new function. This is demonstrated below.

Button showPopUpButton = (Button) findViewById(R.id.buttonShowPopUp);
showPopUpButton.setOnClickListener(new OnClickListener() {

 @Override
 public void onClick(View v) {
  showPopUp2();
 }
});

Adding a Text View

Perphaps you want to use a Pop up window to ask the user to enter their name when they achieve a new high score. To Accomplish this, we can add an EditText to the AlertDialog.

Modify the showPopUp2 code to contain the following right after the setMessage line.

final EditText input = new EditText(this);
input.setSingleLine();
input.setText("");
helpBuilder.setView(input);


Run the app again, and your Pop up will now feature an EditText. If you want, you could modify the listeners for the buttons to take some type of action referencing the value of the edit text.



Setting a Custom Layout for an Alert Dialog

In some situations it may be easier to define a layout in XML and then inflate it for the pop up. This is fairly easy to do.

Create a new layout called popuplayout.xml Then add a couple of checkboxes to the layout.


The source code for the layout is listed below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 android:orientation="vertical">
 <CheckBox android:id="@+id/checkBox2" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:text="CheckBox 1"></CheckBox>
 <CheckBox android:id="@+id/checkBox3" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:text="CheckBox 2"></CheckBox>
 <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:text="CheckBox 3"></CheckBox>
</LinearLayout>

Now, create a new function showPopUp3. This function will show a Pop Up that features our newly created XML layout.

private void showPopUp3() {

 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
 helpBuilder.setTitle(&quot;Pop Up&quot;);
 helpBuilder.setMessage(&quot;This is a Simple Pop Up&quot;);
 
 LayoutInflater inflater = getLayoutInflater();
 View checkboxLayout = inflater.inflate(R.layout.popuplayout, null);
 helpBuilder.setView(checkboxLayout);
 
 helpBuilder.setPositiveButton(&quot;Ok&quot;,
   new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {
     // Do nothing but close the dialog
    }
   });

 // Remember, create doesn't show the dialog
 AlertDialog helpDialog = helpBuilder.create();
 helpDialog.show();


Once again, modify the ClickListener for the showPopUp button to call our new function.

Button showPopUpButton = (Button) findViewById(R.id.buttonShowPopUp);
showPopUpButton.setOnClickListener(new OnClickListener() {

 @Override
 public void onClick(View v) {
  showPopUp3();
 }
});

Shown below is a screenshot of the output.

An Android Pop Up (AlertDialog) featuring a layout inflated from XML
 Listed below is the complete source file for the MainActivity.


package com.dreamdom.popup;

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

public class MainActivity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  Button showPopUpButton = (Button) findViewById(R.id.buttonShowPopUp);
  showPopUpButton.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    showPopUp3();
   }
  });
 }

 private void showSimplePopUp() {

  AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
  helpBuilder.setTitle("Pop Up");
  helpBuilder.setMessage("This is a Simple Pop Up");
  helpBuilder.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {

     public void onClick(DialogInterface dialog, int which) {
      // Do nothing but close the dialog
     }
    });

  // Remember, create doesn't show the dialog
  AlertDialog helpDialog = helpBuilder.create();
  helpDialog.show();
 }

 private void showPopUp2() {

  AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
  helpBuilder.setTitle("Pop Up");
  helpBuilder.setMessage("This is a Simple Pop Up");
  
  final EditText input = new EditText(this);
  input.setSingleLine();
  input.setText("");
  helpBuilder.setView(input);
  
  helpBuilder.setPositiveButton("Positive",
    new DialogInterface.OnClickListener() {

     public void onClick(DialogInterface dialog, int which) {
      // Do nothing but close the dialog
     }
    });

  helpBuilder.setNegativeButton("Negative", new DialogInterface.OnClickListener() {

   @Override
   public void onClick(DialogInterface dialog, int which) {
    // Do nothing
   }
  });
  
  helpBuilder.setNeutralButton("Neutral", new DialogInterface.OnClickListener() {

   @Override
   public void onClick(DialogInterface dialog, int which) {
    // Do nothing
   }
  });

  // Remember, create doesn't show the dialog
  AlertDialog helpDialog = helpBuilder.create();
  helpDialog.show();

 }
 
 private void showPopUp3() {

  AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
  helpBuilder.setTitle("Pop Up");
  helpBuilder.setMessage("This is a Simple Pop Up");
  
  LayoutInflater inflater = getLayoutInflater();
  View checkboxLayout = inflater.inflate(R.layout.popuplayout, null);
  helpBuilder.setView(checkboxLayout);
  
  helpBuilder.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {

     public void onClick(DialogInterface dialog, int which) {
      // Do nothing but close the dialog
     }
    });

  // Remember, create doesn't show the dialog
  AlertDialog helpDialog = helpBuilder.create();
  helpDialog.show();
 }
}


------------------------------------------------------------

We create these tutorials in our free time. If you like what you see please consider buying us a cup of coffee so we can keep creating useful material. Click on the image below to make a donation via Paypal.

8 comments:

  1. Hi, Thank you for your tutorial. It helped me solving my problem! But I have another question, for the last part, alert dialog with checkboxes, what if I want the checkbox values to be the data I query from my SQlite database instead of fixed text?

    ReplyDelete
    Replies
    1. Just replace the text with a variable which u got from your database

      Cerberus

      Delete
  2. Any suggestions for Han's question. I have the same issue.

    ReplyDelete
  3. Thanks! Hove to checked checkbox item before popup dialog show?

    ReplyDelete
  4. Hello, Great tutorial its well detailed but I have a question, how to output an alertdialog box in list form where the user could press the selected item in the list?. :D thanks in advance

    ReplyDelete
    Replies
    1. you could create a ListView with an onClicklistener, and put that inside the alertdialog like the checkboxes (by using an .xml)

      Delete
  5. Please continue this great work and I look forward to more of your awesome blog posts. 9apps games

    ReplyDelete