Android AlertDialog Example

By using android alert dialog example we can perform some action according to that dialog.

Android AlertDialog Example :-

To ask user permission for "Exit ?" we can use Android AlertDialog with Yes or No Button. So, by clicking Yes we can Exit the Application  and by clicking No we need not to do any action.

[sourcecode language="java"]
public class ExampleApp extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Do you want to close this window ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//  Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Title");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
}
[/sourcecode]

The output will looks like

alertdialogexample

Comments

Hi Rich, this refers to the

Hi Rich,
this refers to the current activity.
If you are creating alert dialog in some other page that extends other then activity,
then you need to send activity in parameter to that class and then set that activity to alert builder.

Questions ?..

Hi Pedro, There is no much

Hi Pedro,
There is no much difference in execution of having separate variable for current class instance.Nothing wrong of having this,But to your matter of concern it occupies added memory for variable thisClass.You can this variable for your understanding.

Thanks Dede! much happy to

Thanks Dede! much happy to hear this from u :)

Thanks Sankar :)

Thanks Sankar :)