Home  >  Android

Android AlertDialog Example with Theme, Icon and DialogInterface.OnClickListener

By Arvind Rai, August 02, 2015
On this page we will provide Android AlertDialog example with theme, icon and DialogInterface.OnClickListener. Instantiate AlertDialog.Builder to set title, icon button etc. These act as OK, Cancel, Yes, No etc button and on click of which an action is performed. To perform it DialogInterface.OnClickListener provides onClick() method which is implemented. Here we will also see how to use different themes provided by android.

AlertDialog

android.app.AlertDialog is used to create alert dialog with title, message and one or two buttons. These buttons will listen events using DialogInterface.OnClickListener.

Themes Provided by Android

AlertDialog has some constants that provides alert theme.
THEME_DEVICE_DEFAULT_DARK
THEME_DEVICE_DEFAULT_LIGHT
THEME_HOLO_DARK
THEME_HOLO_LIGHT
THEME_TRADITIONAL 



Instantiate AlertDialog.Builder

To set title, message, icon, button etc we need AlertDialog.Builder that can be instantiated by using two constructors.
1. AlertDialog.Builder(Context context) : Here we pass context only.
2. AlertDialog.Builder(Context context, int theme): This also accepts theme as an argument. It can be like
AlertDialog.Builder builder = new AlertDialog.Builder(context,AlertDialog.THEME_HOLO_DARK); 

Set Title and Icon

Using builder we can set tile and icon as follows
builder.setTitle("My Alert Title");
builder.setIcon(R.drawable.ic_launcher); 
If we don't set title, icon is not displayed.

Set Message

Set the message using method setMessage() of AlertDialog.Builder class as follows.
builder.setMessage("This demo is for you."); 

Use of setCancelable() Method

setCancelable() accepts Boolean argument and decides whether dialog is cancelable or not. Default is true.
builder.setCancelable(false); 

Use of DialogInterface.OnClickListener() Method

android.content.DialogInterface.OnClickListener interface has a method
onClick(DialogInterface dialog, int which) 
which performs action when button on dialog is clicked.

Use setPositiveButton() and setNegativeButton() to Display OK and YES-NO

To set buttons, we use
AlertDialog.Builder setPositiveButton (CharSequence text, DialogInterface.OnClickListener listener)
AlertDialog.Builder setNegativeButton (CharSequence text, DialogInterface.OnClickListener listener)  
Find the code snippet.
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int arg1) {
			Toast toast = Toast.makeText(context, "You are a HAPPY person.", Toast.LENGTH_LONG);
			toast.show();
			dialog.cancel();
		}
        })
	.setNegativeButton("No", new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int arg1) {
			Toast toast = Toast.makeText(context, "You are a SAD person.", Toast.LENGTH_LONG);
			toast.show();
			dialog.cancel();
		}
	}); 
If we want to show only one button, then use only one method.

Show Dialog using AlertDialog.show() and Cancel using DialogInterface.cancel()

Finally to show alert dialog, we call AlertDialog.show() as follows.
AlertDialog alertDialog = builder.create();
alertDialog.show();  
To cancel the dialog, use below method on button click event.
DialogInterface.cancel() 

Complete Example

AlertDialogUtil.java
package com.concretepage;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;
public class AlertDialogUtil {
   public static AlertDialog singleButton(Context context){
	AlertDialog.Builder builder = new AlertDialog.Builder(context,
				AlertDialog.THEME_HOLO_DARK);
        builder.setTitle("My Alert Title")
        .setIcon(R.drawable.ic_launcher)
        .setCancelable(false)
        .setMessage("This demo is for you.")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int arg1) {
			dialog.cancel();
		}
	});
	AlertDialog alertDialog = builder.create();
	return alertDialog;
   }
   
   public static AlertDialog doubleButton(final Context context){
	AlertDialog.Builder builder = new AlertDialog.Builder(context,
				AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        builder.setTitle("My Alert Title")
        .setIcon(R.drawable.ic_launcher)
        .setCancelable(false)
        .setMessage("Are you happy?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int arg1) {
			Toast toast = Toast.makeText(context, "You are a HAPPY person.", Toast.LENGTH_LONG);
			toast.show();
			dialog.cancel();
		}
        })
	.setNegativeButton("No", new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int arg1) {
			Toast toast = Toast.makeText(context, "You are a SAD person.", Toast.LENGTH_LONG);
			toast.show();
			dialog.cancel();
		}
	});
	AlertDialog alertDialog = builder.create();
	return alertDialog;
   }
} 
MainActivity.java
package com.concretepage;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
	AlertDialog alertDialog = null;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		OnClickListener listener = new OnClickListener() {
    	           public void onClick(View view) {
		      switch (view.getId()) {
		        case R.id.onebtn: 
		       	    alertDialog = AlertDialogUtil.singleButton(MainActivity.this);
			    alertDialog.show();
		            break;
		        case R.id.twobtn: 
		            alertDialog = AlertDialogUtil.doubleButton(MainActivity.this);
			    alertDialog.show();
		            break;
	              }
    	           }
    	        };
    	        findViewById(R.id.onebtn).setOnClickListener(listener);
    	        findViewById(R.id.twobtn).setOnClickListener(listener);
	}
} 
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="16"/>
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity  android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C98C00"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/onebtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn1_msg" />
    <Button
        android:id="@+id/twobtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn2_msg" />
</LinearLayout> 
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Concrete Page</string>
    <string name="btn1_msg">Alert Dialog- Single Button</string>
    <string name="btn2_msg">Alert Dialog- Double Button</string>    
</resources>  

Output

Android AlertDialog Example with Theme, Icon and DialogInterface.OnClickListener
Android AlertDialog Example with Theme, Icon and DialogInterface.OnClickListener
Android AlertDialog Example with Theme, Icon and DialogInterface.OnClickListener

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us