In this article, I will explain about displaying a dialog window. There are many times when a user needs to display a dialog window to get a confirmation from the end user. To create an environment for Android application development and get an idea about activities life cycle, refer to the below articles,
In MainActivity.java class, add an array,
- CharSequence[] items={"Wipro", "IBM", "TCS"};
- boolean[] itemChecked = new boolean [items.length];
To create a dialog window, override the onCreateDialog() protected method which is defined in the Activity base class.
- protected Dialog onCreateDialog(int id){
- switch(id) {
- case 0:
- return new AlertDialog.Builder(this)
- .setIcon(R.drawable.i1)
- .setTitle("This is a simple dialog!")
- .setPositiveButton("OK",
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface, int i) {
- Toast.makeText(getBaseContext(), "OK clicked!", Toast.LENGTH_SHORT).show();
- }
- }
- )
- .setNegativeButton("Cancel",
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface, int i) {
- Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show();
- }
- }
- )
- .setMultiChoiceItems(items, itemChecked,
- new DialogInterface.OnMultiChoiceClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface, int i, boolean b) {
- Toast.makeText(getBaseContext(),items[i]+ (b?" is checked":" is unchecked"),Toast.LENGTH_SHORT).show();
- }
- }
-
- ).create();
- }
- return null;
- }
Below method is called when you call the showDialog() method.
- public void onClick(View v)
- {
- showDialog(0);
- }
The onCreateDialog() method is a callback for creating dialogs that are managed by the activity. When showDialog() method is called, this callback onCreateDialog() method is invoked. The showDialog() method accepts an integer as an argument to display a particular dialog. We have used switch statement to identify the different types of dialogs to create. To create a dialog, AlertDialog class, Builder constructor is used.
In the above code, OK and Cancel are sets using the setPositionButton() and setNegativeButton(). A user has the option to select multiple options by using setMultipleChioceItems() method. When an option is checked or unchecked by the user, he/she gets the message that selected option is checked or unchecked.
Click on above button display in the screenshot,
If user unchecks the option,
In the next article, I will explain about Progress Dialog.