Android development primer: Creating Alert Dialogs in Android

This entry is part 13 of 50 in the series Android Development Primer

In Android devices, probably the thing that we come across most frequently is Alert Dialog Boxes. If you are not familiar with an Alert Dialog Box, here’s what it looks like on an Eclair emulator.

alert1

You should know that the Dialog’s title, text and the buttons are customizable and can be made to read anything.
We’ll see how to do it in a minute. So open an activity and start coding. Complete Source Code is at the bottom.

  • For the layout of the activity insert a button. We will make the Alert Dialog appear when the button is pressed.
  • Set the content view of the Activity and add declare the button from the layout in the java file.
  • We will now set the onClickListener() attribute of the button. Write the following code in the onClick() function of the onClickListener() attribute.
    AlertDialog.Builder alert = new AlertDialog.Builder(Main.this);
    				alert.setTitle("Test Alert Dialog").setMessage(msg).setPositiveButton("Yes",
    						new DialogInterface.OnClickListener() {
    
    							@Override
    							public void onClick(DialogInterface dialog, int which) {
    								Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_LONG).show();
    							}
    						}).setNegativeButton("No",
    								new DialogInterface.OnClickListener() {
    
    									@Override
    									public void onClick(DialogInterface dialog, int which) {
    										Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
    									}
    								});
    				alert.show();
    
  • If it is not clear have a look at the complete Source Code at the bottom to understand what you need to do.
  • If you take some time and go through the AlertDialog code snippet, you can see that the components used in it are quite mnemonic. The functions such as setTitle()setMessage()setPositiveButton()setNegativeButton() represent exactly what they do. However in case you have an issue understanding them, drop a comment and I will explain it the best I can.
  • Save the activity and execute in an emulator/device.
  • Below images shows the results of clicking the Yes and No button on the Alert Dialog respectively.

alert2   alert3

COMPLETE SOURCE CODE

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <Button
        android:id="@+id/but"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="Button" />

</RelativeLayout>

Main.java

package com.nero.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button but = (Button) findViewById(R.id.but);
        final String msg="This is a test Alert Dialog Box";
        but.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder alert = new AlertDialog.Builder(Main.this);
				alert.setTitle("Test Alert Dialog").setMessage(msg).setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_LONG).show();
							}
						}).setNegativeButton("No",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {
										Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
									}
								});
				alert.show();
			}
			});

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Here, we are making a simple Toast appear on the Click of the Positive or the Negative button of the Alert Dialog. Once you are into making complex applications, you will be doing much more than this with the Alert Dialog.

Series Navigation<< Android development primer: Know the AndroidManifest.xmlAndroid development primer: Creating layouts for Alert Dialog >>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

41,728 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>