Could anyone please explain what context should i use the AlertDialog.Builder class? I am new to android app development and I frankly don't understand which context to use when?
Say, I want to create an object for AlertDialog.Builder class -
AlertDialog.Builder ab = new AlertDialog.Builder();
ab.setMessage("Test");
ab.show();
What context should I use it in? Does it differ if I use the Alert Dialog onCreate
or OnClickListener
or in the handler of any such event?
You should use the context of the Activity that it's executed from. In other words, just use YourNameOfActivity. this as context.
Alert Dialog code has three methods:setTitle() method for displaying the Alert Dialog box Title. setMessage() method for displaying the message. setIcon() method is used to set the icon on the Alert dialog box.
AlertDialog. A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. DatePickerDialog or TimePickerDialog. A dialog with a pre-defined UI that allows the user to select a date or time.
AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .
You should use the context of the Activity that it's executed from. In other words, just use YourNameOfActivity.this
as context.
In the first version of my app I made the mistake of not using onCreateDialog and instead built and showed the dialogs myself. If you do it yourself you have to take care of things like dismissing the dialog before the activity is finish()ed otherwise a window will leak.
I would override onCreateDialog in your activity and return ab.create() (not show()). onCreateDialog will then handle showing the dialog and you'll just have to call showDialog(id).
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Test")
.show;
(or) if u want (yes,no) button means use this
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.show();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With