Android Dialog

Android Dialog class is the base class for all dialogs in android and was added in Android API 1.0.

It’s a public class that extends the java.lang.Object.

This class implements 4 interfaces:

  1. DialogInterface.
  2. Window.Callback.
  3. KeyEvent.Calllback.
  4. View.OnCreateContextMenuListener.

The Dialog class resides in the android.app package.

Some of the direct subclasses of this class include:

No. SubClass Type SubClass
1. AlertDialog Direct
2. AppCompatDialog Direct
3. CharacterPickerDialog Direct
4. MediaRouteChooserDialog Direct
5. Presentation Direct
6. AlertDialog Indirect
7. BottomSheetDialog Indirect
8. DatePickerDialog Indirect
9. MediaRouteControllerDialog Indirect
10. ProgressDialog Indirect
11. TimePickerDialog Indirect

===

Dialog HowTo examples

1. How to create a custom progress dialog.

Here’s an example class that shows how to create a custom dialog. This is a dialog that can be used for loading.

Obviously you start by extends the android.app.Dialog class. You override two constructors, one taking a context object only, the other a context object and a theme integer.

Here’s the full code:

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.jkapp.R;

/**
 * Load dialog with animation
 */
public class CustomLoadDialog extends Dialog {
     private Animation animation;
     private static ImageView imageView ;
     private static CustomLoadDialog dialog;
    private static Handler mHandler = new Handler();
    public CustomLoadDialog(Context context) {
        super(context);
    }

    public CustomLoadDialog(Context context, int theme) {
        super(context, theme);
    }

    /**
     * Called when the window focus changes
     */
    public void onWindowFocusChanged(boolean hasFocus) {
         imageView = (ImageView) findViewById(R.id.spinnerImageView);
         animation = AnimationUtils.loadAnimation(getContext(), R.anim.spinner);
          animation.setFillAfter(true);
          if(animation!=null)
          {
              imageView.startAnimation(animation);

    }

    /**
     * 
     * @param message
     */
    public void setMessage(CharSequence message) {
        if (message != null && message.length() > 0) {
            findViewById(R.id.message).setVisibility(View.VISIBLE);
            TextView txt = (TextView) findViewById(R.id.message);
            txt.setText(message);
            txt.invalidate();
        }
    }

    /**
     * 
     * @param context
     * @param message
     * @param cancelable
     * @param cancelListener
     * @return
     */
    public static CustomLoadDialog show(Context context, CharSequence message, boolean cancelable, OnCancelListener cancelListener,int resId) {
        dialog = new CustomLoadDialog(context, R.style.Custom_Progress);
        dialog.setTitle("");
//      dialog.setContentView(R.layout.progress_custom);
        dialog.setContentView(resId);
        if (message == null || message.length() == 0) {
            dialog.findViewById(R.id.message).setVisibility(View.GONE);
        } else {
            TextView txt = (TextView) dialog.findViewById(R.id.message);
            txt.setText(message);
        }
        // Press the back button to cancel
        dialog.setCancelable(cancelable);
        // Listening back key handling
        dialog.setOnCancelListener(cancelListener);
        // Set centered
        dialog.getWindow().getAttributes().gravity = Gravity.CENTER;
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        // Set background layer transparency
        lp.dimAmount = 0.2f;
        dialog.getWindow().setAttributes(lp);
        // dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

        if(!((Activity) context).isFinishing())
        {
            //show dialog
            dialog.show();
        }
        return dialog;
    }

    public  static void dismisDialog(){
        if(imageView!=null)
            imageView.clearAnimation();
        if(dialog!=null)
        {
            dialog.dismiss();
            dialog= null;
        }

    }

}

 

Android Custom Dialog With Images and Text

Android comes default with an alert dialog.Thats good since majority of simple stuff it can asily display,in maybe 4-5 lines of code.But when it comes custom views,it falls short flatly.Luckily its just as easier to display a custom view as a dialog.Its what we show here,using custom layout without any third party libraries.

Intro

  • A simple alert dialog with images and text in android.
  • We have a video tutorial for this example below.You can also view the demo over there.
  • We’ve used Android Studio as our IDE.
  • The full source code is above for download.The instructions for importing to your android studio is below.

Tools Used

  • IDE : Android Studio
  • OS : Windows 8

Let’s go.

1. MainActivity


Here’s our MainActivity :

package com.tutorials.hp.customdialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Dialog dialog;
    TextView showBtn,cancelBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //CREATE DIALOG
        createDialog();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //show
                dialog.show();
            }
        });

        //SHOW BTN CLIKCED
        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"CLICKED",Toast.LENGTH_LONG).show();
            }
        });

        //CANCEL
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               dialog.dismiss();
            }
        });

    }

    private void createDialog()
    {
        dialog=new Dialog(this);

        //SET TITLE
        dialog.setTitle("Player");

        //set content
        dialog.setContentView(R.layout.custom_layout);

        showBtn= (TextView) dialog.findViewById(R.id.showTxt);
        cancelBtn= (TextView) dialog.findViewById(R.id.cancelTxt);
    }
}

2. Our Layouts

Custom Dialog Layout

Then we have our Custom Dialog layout here.Its this layout that gets inflated to our dialog.So you can customize it to your wishes.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android_orientation="vertical" android_layout_width="match_parent"
    android_layout_height="match_parent">

    <ImageView
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_padding="5dp"
        android_src="@drawable/carrick"
        android_id="@+id/imageView" />

    <TextView
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_paddingBottom="20dp"
        android_paddingLeft="24dp"
        android_paddingRight="24dp"
        android_paddingTop="24dp"
        android_textAppearance="?android:attr/textAppearanceLarge"
        android_text="Michael Carrick"
        android_id="@+id/nameTxtt" />

    <TextView
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_paddingBottom="24dp"
        android_paddingLeft="24dp"

        android_paddingRight="24dp"
        android_textAppearance="?android:attr/textAppearanceMedium"
        android_text="Is a Midfielder.Joined from Totenham in 2006. "
        android_id="@+id/contentTxt" />

    <LinearLayout
        android_layout_width="match_parent"
        android_layout_height="52dp"
        android_gravity="center_vertical|end"
        android_orientation="horizontal"
        android_padding="8dp">

        <TextView
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_height="48dp"
            android_clickable="true"
            android_padding="5dp"
            android_textAppearance="?android:attr/textAppearanceMedium"
            android_gravity="center_vertical|center_horizontal"
            android_text="Show"
            android_textColor="@color/colorAccent"
            android_id="@+id/showTxt" />

        <TextView
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_height="48dp"
            android_clickable="true"
            android_padding="5dp"
            android_textAppearance="?android:attr/textAppearanceMedium"
            android_gravity="center_vertical|center_horizontal"
            android_text="Cancel"
            android_textColor="@color/colorAccent"
            android_id="@+id/cancelTxt" />

    </LinearLayout>

</LinearLayout>

How To Run

  1. Download the project.
  2. You’ll get a zipped file,extract it.
  3. Open the Android Studio.
  4. Now close, already open project.
  5. From the Menu bar click on File >New> Import Project.
  6. Now Choose a Destination Folder, from where you want to import project.
  7. Choose an Android Project.
  8. Now Click on “OK“.
  9. Done, your done importing the project,now edit it.

Download

Introduction to AlertDialog

An AlertDialog is a subclass of a Dialog that can display one, two or three buttons.

AlertDialogs don’t require any layout.

AlertDialog was added in Android API level 1.

It resides in the android.app package.

package android.app;

AlertDialog derives from the android.app.Dialog class:

public class AlertDialog 
extends Dialog..{}

AlertDialog implements the DialogInterface interface:

public class AlertDialog 
extends Dialog implements DialogInterface

===

AlertDialog SubClasses:

Here are some of the classes that directly derive AlertDialog:

No. Class Description
1. DatePickerDialog A simple Dialog that has a DatePicker.
2. ProgressDialog A dialog that shows a progress indicator and an optional text message or view.
3. TimePickerDialog A Dialog that prompts the user for the time of the day using TimePicker.

Use of AlertDialog

  1. To display alert or any information.

Creating AlertDialog

To create an AlertDialog you use the android.app.AlertDialog.Builder class.

  1. First you instantiate the AlertDialog.Builder:
        AlertDialog.Builder myBuilder=new AlertDialog.Builder(this);
  2. Then you create the AlertDialog using the create() method:
        AlertDialog myDialog=myBuilder.create();

Displaying Title and Message

To display only a String you can just use the setMessage() method and to display title you can use the setTitle() method.

        myBuilder.setTitle(R.string.my_title).setMessage(R.string.my_message);

Display Complex View in AlertDialog

To display a more complex view, you can look up a FrameLayout called custom and add your view to it.

FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
 fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));

Showing AlertDialog

To show the AlertDialog you use the show() method:

myDialog.show();

Creating AlertDialog with Buttons

AlertDialogs can have buttons as well as content. So far we’ve looked at how to display content and title.

However, the AlertDialog.Builder also allows us create buttons:

  1. Positive Button – We can create positive button using the setPositiveButton() method of the AlertDialog.Builder class.
myBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "OK clicked", Toast.LENGTH_SHORT).show();
            }
        });
  1. Negative Button – We can create negative button using the setNegativeButton() method of the AlertDialog.Builder class.
myBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                myDialog.dismiss();
            }
        });
  1. Neutral Button – We can create neutral button using the setNeutralButton() method of the AlertDialog.Builder class.
myBuilder.setNeutralButton("Neutral", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

Android AlertDialog Examples

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.LayoutRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

public class KDialog {

    public static void showImgInDialog(Context context, Bitmap bitmap) {
        ImageView imageView = new ImageView(context);
        imageView.setImageBitmap(bitmap);
        new AlertDialog.Builder(context)
                .setView(imageView)
                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    public static void showMsgDialog(final Context context, final String content) {
        new android.os.Handler(Looper.getMainLooper())
                .post(new Runnable() {
                    @Override
                    public void run() {
                        new AlertDialog.Builder(context)
                                .setMessage(content)
                                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
                    }
                });

    }

    public static void showCustomViewDialog(final Context context, final String title, final View view,
                                            final DialogInterface.OnClickListener positiveListener, final DialogInterface.OnClickListener negativeListener) {
        new Handler(Looper.getMainLooper())
                .post(new Runnable() {
                    @Override
                    public void run() {
                        new AlertDialog.Builder(context)
                                .setTitle(title)
                                .setView(view)
                                .setPositiveButton("确认", positiveListener)
                                .setNegativeButton("取消", negativeListener)
                                .show();
                    }
                });
    }

    public static void showSingleChoiceDialog(final Context context, final String title, CharSequence[] items, final SingleSelectedCallback callback) {
        final int[] selectedIndex = new int[1];
        new AlertDialog.Builder(context)
                .setTitle(title)
                .setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selectedIndex[0] = which;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            callback.singleSelected(selectedIndex[0]);
                        }
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }

    public static void showMultiChoicesDialog(final Context context, final String title, CharSequence[] items, final MultiSelectedCallback callback) {
        final int[] selectedItems;
        final boolean[] selected = new boolean[items.length];
        new AlertDialog.Builder(context)
                .setTitle(title)
                .setMultiChoiceItems(items, new boolean[items.length], new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        selected[which] = isChecked;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int size = selected.length;
                        List<Integer> selectedList = new ArrayList<>();
                        if (callback != null) {
                            for (int i = 0; i < size; i++) {
                                if (selected[i]) {
                                    selectedList.add(i);
                                }
                            }
                            if (selectedList != null && selectedList.size() > 0) {
                                callback.multiSelected(selectedList);
                            } else {
                                callback.selectedNothing();
                            }
                        }
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }

    private static ProgressDialog progressDialog;

    public static void showProgressDialog(final Context context, int progress){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(context);
        }
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setProgress(progress);
        progressDialog.show();

        if (progress >= 100){
            if (progressDialog != null && progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }

    public interface SingleSelectedCallback {
        void singleSelected(int index);
    }

    public interface MultiSelectedCallback {
        void multiSelected(List<Integer> list);

        void selectedNothing();
    }

}

 

Android Dialogs – AlertDialog with Buttons

In this class we see how to show an alert dialog with buttons. AlertDialog allows us display simple dialogs without us creating any layout.

Our alert dialog in this case will have two buttons: a positive button and a negative button.

 

We then handle the onClick events for these buttons.

1. Create Project

In your android studio create an empty activity. If you are not sure how to do that check this tutorial.

In our generated project we will have one class: MainActivity and one layout activity_main.xml.

3. activity_main.xml

First we will have our layouts here.
This layout will get inflated into our activity.

At the root we have relativelayout. We add our TextView as well as a button inside the layout.

When the button is clicked we will display our alertdialog with buttons.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    tools_context="info.camposha.mysimplealertdialogbuttons.MainActivity">

    <TextView
        android_id="@+id/headerLabel"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_alignParentTop="true"
        android_layout_centerHorizontal="true"
        android_fontFamily="casual"
        android_text="Simple AlertDialog Buttons"
        android_textAllCaps="true"
        android_textSize="24sp"
        android_textStyle="bold" />

    <Button
        android_id="@+id/showAlertID"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_text="Show Alert Dialog"
        android_layout_centerHorizontal="true"
        android_layout_centerVertical="true"
    />

</RelativeLayout>

3. MainActivity.java

Here’s our main activity code:

package info.camposha.mysimplealertdialogbuttons;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/*
ANDROID ALERTDIALOG WITH BUTTONS
 */
public class MainActivity extends Activity {
    /*
     ONCREATE METHOD
      */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //REFERENCE BUTTON AND SHOW IT.
        Button showBtn=findViewById(R.id.showAlertID);
        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlert();
            }
        });
    }
    /*
    CREATE AN ALERT DIALOG AND SHOW IT
     */
    private void showAlert()
    {
        //initialize alertdialog
        AlertDialog myDialog = null;

        //INSTANTIATE ALERTDIALOG BUILDER
        AlertDialog.Builder myBuilder=new AlertDialog.Builder(this);
        myBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "OK clicked", Toast.LENGTH_SHORT).show();
            }
        });
        //final dialog
        final AlertDialog finalDialog = myDialog;
        myBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finalDialog.dismiss();
            }
        });
        //SET PROPERTIES USING METHOD CHAINING
        myBuilder.setTitle("Science Tips").setMessage("Boomerang Nebular is the Coldest region in the Universe");
        //CREATE DIALOG
        myDialog=myBuilder.create();
        //SHOW DIALOG
        myDialog.show();
    }
}

Notes

  1. First we specify the package for our application.
    package info.camposha.mysimplealertdialogbuttons;
  2. Then add our import statements.
  3. Then we create our class called MainActivity and make it derive from android.app.Activity.
    public class MainActivity extends Activity {..}
  4. We’ll create a method called showAlert() that will create our dialog using the AlertDialog.Builder class and then add the buttons. To add the button we use the setPositiveButton() and setNegative() methods. These methods are defined in the AlertDialog.Builder class. We also set the title and message of the dialog using methods defined in the same class.
  5. We finally override the onCreate() method and show the alert dialog when the showBtn button is clicked.

Quick AlertDialog Examples

1. One static method you can reuse

You can reuse this to quickly create your alertdialogs with buttons.

It’s static so you don’t need a class instance. All you need is pass a Context object as well as you custom title and message.

    public static void createInformativeDialog(Context context, String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message)
                .setCancelable(true)
                .setPositiveButton(context.getResources().getString(R.string.action_ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

 

Android Dialogs – AlertDialog with List

Android AlertDialog with List Tutorial.

We will see how to render list items in an alert dialog in android. Java is our programming language.

First understand that AlertDialog is a subclass of the android.app.Dialog class and allows us show simple messages, buttons and even lists in our modal.

With alertdialog we don’t have to create any layout in XML. It has a predefined layout that we can just use with pre-existing Builder class to show message, title and buttons and even lists.

1. Create Project

Create an empty project with android studio.

Check here if you are not sure how to do that.

2. activity_main.xml

Let’s come edit the activity_main.xml which is our layout for the main activity.

We’ll add a header label which is basically a TextView.

We also add a button that will show the dialog which will contain our list.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    tools_context="info.camposha.mysimplealertdialoglist.MainActivity">

    <TextView
        android_id="@+id/headerLabel"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_alignParentTop="true"
        android_layout_centerHorizontal="true"
        android_fontFamily="casual"
        android_text="Android Simple AlertDialog"
        android_textAllCaps="true"
        android_textSize="24sp"
        android_textStyle="bold" />

    <Button
        android_id="@+id/showAlertID"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_text="Show Alert Dialog"
        android_layout_centerHorizontal="true"
        android_layout_centerVertical="true"
    />

</RelativeLayout>

3. MainActivity.java

Here’s our code for our main activity.

package info.camposha.mysimplealertdialoglist;

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

public class MainActivity extends Activity {

    AlertDialog myDialog;

    /*
     ONCREATE METHOD
      */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //REFERENCE BUTTON AND SHOW IT.
        Button showBtn=findViewById(R.id.showAlertID);
        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlert();
            }
        });

    }

    /*
    CREATE AN ALERT DIALOG AND SHOW IT
     */
    private void showAlert()
    {
        //INSTANTIATE ALERTDIALOG BUILDER
        AlertDialog.Builder myBuilder=new AlertDialog.Builder(this);
        //DATA SOURCE
        final CharSequence[] nebulae={"Boomerang","Orion","Witch Head","Ghost Head","Black Widow","Flame","Cone"};
        //SET PROPERTIES USING METHOD CHAINING
        myBuilder.setTitle("Science Tips").setItems(nebulae, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int position) {
                Toast.makeText(MainActivity.this, nebulae[position].toString(), Toast.LENGTH_SHORT).show();
            }
        });
        //CREATE DIALOG
        myDialog=myBuilder.create();
        //SHOW DIALOG
        myDialog.show();
    }
}

Notes.

  1. First we add our package to hold our class.
  2. Secondly we add the imports we require in our project. These include android.app.Activity and android.app.AlertDialog.
  3. Thirdly we create a class that derives from Activity.
    public class MainActivity extends Activity {..}
  4. Then we create an insance field to hold our AlertDialog.
  5. We’ll define a method that will create our alertdialog and show it. We need an AlertDialog.Builder instance for this so we instantiate it, passing in a Context.

We then define a CharSequence array that will hold a bunch of nebulas.

We set the title to our AlertDialog.Builder instance.Then we invoke the setItems() method, passing in the CharSequence array, which is our data source.

When an item from our dialog is clicked,we will show a Toast message.

We then create the dialog using the create() method and show() it.

  1. Finally we override the onCreate() method of our Activity. When our button is clicked, we will show the alert dialog.

 

 

 

 

Share



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )