Using Dialog in Android.

Android Dialog, wish it was simple as MessageBox in C#. LOL !

In fact, the way to use Dialog in Android is quite simple.

3 essential steps:

Step 1: Declare a Dialog Builder
In my example activity, onStart():
AlertDialog.Builder builder = new AlertDialog.Builder(this);

Step 2: Logic to handle event raised from Dialog.

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
enableLocationSettings();
break;
case DialogInterface.BUTTON_NEGATIVE:
finish();
break;
default:
finish();
break;
}

}
};

private void enableLocationSettings() {
Intent locationSettingsIntent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(locationSettingsIntent);
}

Step 3: Show our dialog with our settings.

builder.setMessage("Do you want to turn on GPS ?")
.setPositiveButton("YES", dialogClickListener)
.setNegativeButton("NO", dialogClickListener).setCancelable(false).show();


You could be familiar with Dialog, usually , there are buttons Yes/Accept/OK… and No/Deny/Cancel ….
These 2 groups of buttons called Positive Button and Negative Button group.
What you have to do is handle event corresponding to these buttons.
You may also see the my setting .setCancelable(false)
This is the answer for the question:

How can I prevent users from pressing back button to cancel dialog ?

Here is example project if you want to investigate more details

http://www.mediafire.com/?k0zcb6vbadblcrz

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: