Tag Archives: Android Dialog

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