Warning: include(/home/content/m/i/g/miguel164777/html/domains/mobiledevtuts/wp-content/plugins/wp-super-cache/wp-cache-base.php) [function.include]: failed to open stream: No such file or directory in /home/content/91/14014491/html/domains/mobiledevtuts/wp-content/plugins/wp-super-cache/wp-cache.php on line 53

Warning: include() [function.include]: Failed opening '/home/content/m/i/g/miguel164777/html/domains/mobiledevtuts/wp-content/plugins/wp-super-cache/wp-cache-base.php' for inclusion (include_path='.:/usr/local/php5_3/lib/php') in /home/content/91/14014491/html/domains/mobiledevtuts/wp-content/plugins/wp-super-cache/wp-cache.php on line 53

Warning: include_once(/home/content/m/i/g/miguel164777/html/domains/mobiledevtuts/wp-content/plugins/wp-super-cache/ossdl-cdn.php) [function.include-once]: failed to open stream: No such file or directory in /home/content/91/14014491/html/domains/mobiledevtuts/wp-content/plugins/wp-super-cache/wp-cache.php on line 70

Warning: include_once() [function.include]: Failed opening '/home/content/m/i/g/miguel164777/html/domains/mobiledevtuts/wp-content/plugins/wp-super-cache/ossdl-cdn.php' for inclusion (include_path='.:/usr/local/php5_3/lib/php') in /home/content/91/14014491/html/domains/mobiledevtuts/wp-content/plugins/wp-super-cache/wp-cache.php on line 70
Android Alert Dialog Example Code and Tutorial

Android Alert Dialog Example Code Tutorial

Android alert dialog in application

Android alert dialog with three button options: No, Yes, and Neutral (Cancel)

The Android Dialog Application: What we’ll be making

As pictured above, we will be creating an Android application that has a button and a text box in the home activity. When the user clicks the button an alert dialog with three buttons: No, Cancel, and Yes will pop-up.

The text in the text box will change depending on the user’s selection. Furthermore the user is not able to close the dialog by simply clicking outside of it.

The User’ Interface

As mentioned above what we need is a button and a textview.

res/layout/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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginTop="26dp"
        android:text="Please click on the button to accept the terms of service."
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Activity Code

Here is the code, scroll below it to see the explanation.

MainActivity.java

package com.example.alertdialogexample;

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

public class MainActivity extends Activity implements View.OnClickListener,DialogInterface.OnClickListener{

	private Button b;
	private TextView t;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(this);
        
        t=(TextView)findViewById(R.id.textView1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		AlertDialog ad = new AlertDialog.Builder(this)
		.setMessage("Blah blah blah.\n Fine pring.\n Do you accept all our terms and conditions?")
		.setIcon(R.drawable.ic_launcher)
		.setTitle("Terms of Service")
		.setPositiveButton("Yes", this)
		.setNegativeButton("No", this)
		.setNeutralButton("Cancel", this)
		.setCancelable(false)
		.create();
		
		ad.show();
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		switch(which){
		case DialogInterface.BUTTON_POSITIVE: // yes
			t.setText("You have accepted the TOS. Welcom to the site");
			break;
		case DialogInterface.BUTTON_NEGATIVE: // no
			t.setText("You have denied the TOS. You may not access the site");
			break;
		case DialogInterface.BUTTON_NEUTRAL: // neutral
			t.setText("Please select yes or no");
			break;
		default:
			// nothing
			break;
		}
	}
}

Java Code Explanation

The first thing we need to do is implement OnClickListeners for both the button and dialog, they each have their own method definition.

public class MainActivity extends Activity implements View.OnClickListener,DialogInterface.OnClickListener{

Next we need to assign the views of the button and textview

	private Button b;
	private TextView t;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(this);
        
        t=(TextView)findViewById(R.id.textView1);
    }

We will now fill in the onclick method for the button. It is here were we will build and call our alert dialog from. Using the AlertDialog.Builder method we will set the various parameters for the dialog, some are pretty explanatory, as you’ll see, so I would like to focus on the ones you might not understand at first sight.

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		AlertDialog ad = new AlertDialog.Builder(this)
		.setMessage("Blah blah blah.\n Fine pring.\n Do you accept all our terms and conditions?")
		.setIcon(R.drawable.ic_launcher)
		.setTitle("Terms of Service")
		.setPositiveButton("Yes", this)
		.setNegativeButton("No", this)
		.setNeutralButton("Cancel", this)
		.setCancelable(false)
		.create();

		ad.show();
	}

The methods setPositiveButton, setNegativeButton, and setNeutralButton create our three buttons in the dialog alert. The first parameter of each of this methods is the text for the button, the second parameter is the listener for the button, since we implemented the DialogInterface.OnClickListener class in the MainActivity class or listener object is MainActivity’s object or "this".

The seCancelable method prevents the user from closing the alert dialog by clicking outside of the dialog, the default is "true", I have set it to false however so that the user is not able to perform this operation.

Now let’s take care of the OnClick method for the Dialog. Inside this onclick method we will handle the user’s selection. The OnClick method for the dialog gives us access to two parameters, the dialog object and an integer representing the button that was clicked called "which"

Using the which argument and a switch control flow we will change the text box’s change accordingly. The Android SDK has made available to use a set of constants which can be used to identify the button that was clicked. For example DialogInterface.BUTTON_POSITIVE goes with our "Yes" button that was created using the setPositiveButton method.


	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		switch(which){
		case DialogInterface.BUTTON_POSITIVE: // yes
			t.setText("You have accepted the TOS. Welcom to the site");
			break;
		case DialogInterface.BUTTON_NEGATIVE: // no
			t.setText("You have denied the TOS. You may not access the site");
			break;
		case DialogInterface.BUTTON_NEUTRAL: // neutral
			t.setText("Please select yes or no");
			break;
		default:
			// nothing
			break;
		}
	}

And that’s how you make an alert dialog in android.

Related posts: