
Dialogs in Android. Part 1
- From the sandbox
- Tutorial
Good afternoon / evening / morning, dear Habravites and you,% username%!
I am developing Android applications, I love this operating system and want to share my experience of using dialog boxes in my projects. First of all, thisarticle is a note very useful for beginners in the field of development for Android.
Also, for beginners in this industry, I recommend first reading this post by the respected Hoorsh .
And now we will begin to consider this issue (which has several pitfalls) under the cut.
Dialog is a class that belongs to the Android SDK and helps us, meremortal programmers, work with dialog boxes in Android. The Dialog class has 4 subclasses:
On the first of this list, AlertDialog we will stop in more detail.
To create the AlertDialog dialog box, we need an instance of the Builder class to help us:
Now that we have the builder, we can “build” our own dialog box. You can write many different parameters in the dialog box options, but these are the main ones:
An example of creating an AlertDialog:
In this example, I used setCancelable (true) - this allows the user to close the dialog box using the hardware Back button. I also created a listener for the affirmative button and used the create () method. The create () method returns a ready-made dialog box with your parameters as an instance of the AlertDialog class.
So we have created a dialog box! The next task is to show it to the user. There are several options here:
The second method suits us better, but writing a bunch of different Buider and AlertDialog in the main activity spoils the readability of the code. Therefore, it is more expedient to put the creation and processing of dialog boxes into a new class, for example:
The only note about this code will be about using the setView (View view) method in the IDD_SETTINGS dialog. AlertDialog, like all other dialogs, has one nice feature - you can set your own Layout, which allows you to completely modify the dialog boxes and their contents. There is one pitfall here: you will have to perform the processing of the elements of this Layout exactly in the Activity where you call this dialog box. For example, I show the IDD_SETTINGS dialog box in MainActivity with a Layout named settings:
Accordingly, I load this window into MainActivity:
The initSettings method of the MainActivity class in this case will look like this:
Well, then process your objects as you please.
1) AlertDialog is suitable for most purposes of dialogs
2) AlertDialog can take the form of layout with any objects
3) It is much better to use a separate class for dialogs and use AlertDialog.show ()
4) Custom layout objects are processed in the activity that caused the dialog
In the next Part of this article will talk about DialogFragment, which has been included in the Android SDK since 3.0 Honeycomb. I hope this article helps beginners and not so much in their quests to conquer Google Play.
This is my first article for Habr, so I accept any constructive criticism. Thanks in advance.
I am developing Android applications, I love this operating system and want to share my experience of using dialog boxes in my projects. First of all, this
Also, for beginners in this industry, I recommend first reading this post by the respected Hoorsh .
And now we will begin to consider this issue (which has several pitfalls) under the cut.
Dialog
Dialog is a class that belongs to the Android SDK and helps us, mere
- AlertDialog: this is a dialog box for various application messages, for example, “Do you want to buy my application?” or something like that. AlertDialog supports three buttons - affirmative (OK), negative (Cancel) and neutral (Later).
- ProgressDialog: this is a dialog box for displaying the execution of various processes, loading, for example.
- DatePickerDialog: A dialog box prompts the user to select a date.
- TimePickerDialog: a dialog box prompts the user to select a time
On the first of this list, AlertDialog we will stop in more detail.
Alertlerialog
To create the AlertDialog dialog box, we need an instance of the Builder class to help us:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Now that we have the builder, we can “build” our own dialog box. You can write many different parameters in the dialog box options, but these are the main ones:
- setTitle (int resID) - sets the title of the dialog box, takes a link to a resource or a string as arguments.
- setMessage (int resID) - sets a message in a dialog box, also accepts a link to a resource or a string.
- setPositiveButton (int textID, DialogInterface.OnClickListener listener) - sets an affirmative button on your dialog box with the resource text textID and listener listener. The setNegativeButton and setNeutralButton methods are identical, with the difference in the purpose of the buttons.
An example of creating an AlertDialog:
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.dialog_about_title);
builder.setMessage(R.string.dialog_about_message);
builder.setCancelable(true);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { // Кнопка ОК
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); // Отпускает диалоговое окно
}
});
AlertDialog dialog = builder.create();
In this example, I used setCancelable (true) - this allows the user to close the dialog box using the hardware Back button. I also created a listener for the affirmative button and used the create () method. The create () method returns a ready-made dialog box with your parameters as an instance of the AlertDialog class.
So we have created a dialog box! The next task is to show it to the user. There are several options here:
- showDialog (AlertDialog dialog) is the easiest way to show a dialog box, but since version 3.0, Android developers do not recommend using this method, and as a result you get a warning that you can bypass only @SurpressWarning, which is not entirely good.
- AlertDialog dialog.show () is an alternative way to show a window; for this, the result of the Builder.create () method must lie in the dialog instance.
The second method suits us better, but writing a bunch of different Buider and AlertDialog in the main activity spoils the readability of the code. Therefore, it is more expedient to put the creation and processing of dialog boxes into a new class, for example:
public class DialogScreen {
public static final int IDD_ABOUT = 1; // Идентификаторы диалоговых окон
public static final int IDD_SETTINGS = 2;
public static final int IDD_RATE = 3;
public static AlertDialog getDialog(Activity activity, int ID) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
switch(ID) {
case IDD_ABOUT: // Диалоговое окно About
builder.setTitle(R.string.dialog_about_title);
builder.setMessage(R.string.dialog_about_message);
builder.setCancelable(true);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { // Кнопка ОК
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); // Отпускает диалоговое окно
}
});
return builder.create();
case IDD_RATE: // Диалоговое окно Rate the app
builder.setTitle(R.string.dialog_rate_title);
builder.setMessage(R.string.dialog_rate_message);
builder.setCancelable(true);
builder.setPositiveButton(R.string.dialog_rate_ok, new DialogInterface.OnClickListener() { // Переход на оценку приложения
@Override
public void onClick(DialogInterface dialog, int which) {
// Переход
dialog.dismiss();
}
});
builder.setNeutralButton(R.string.dialog_rate_cancel, new DialogInterface.OnClickListener() { // Оценить приложение потом
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); // Отпускает диалоговое окно
}
});
builder.setNegativeButton(R.string.dialog_rate_buy, new DialogInterface.OnClickListener() { // Переход на покупку AdFree версии
@Override
public void onClick(DialogInterface dialog, int which) {
// Переход
dialog.dismiss();
}
});
return builder.create();
case IDD_SETTINGS: // Диалог настроек
View view = activity.getLayoutInflater().inflate(R.layout.settings, null); // Получаем layout по его ID
builder.setView(view);
builder.setTitle(R.string.dialog_settings_title);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { // Кнопка ОК
public void onClick(DialogInterface dialog, int whichButton) {
MainActivity.doSaveSettings(); // Переход в сохранение настроек MainActivity
dialog.dismiss();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { // Кнопка Отмена
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setCancelable(true);
return builder.create();
default:
return null;
}
}
}
The only note about this code will be about using the setView (View view) method in the IDD_SETTINGS dialog. AlertDialog, like all other dialogs, has one nice feature - you can set your own Layout, which allows you to completely modify the dialog boxes and their contents. There is one pitfall here: you will have to perform the processing of the elements of this Layout exactly in the Activity where you call this dialog box. For example, I show the IDD_SETTINGS dialog box in MainActivity with a Layout named settings:
Accordingly, I load this window into MainActivity:
AlertDialog dialog = DialogScreen.getDialog(this, DialogScreen.IDD_SETTINGS);
dialog.show();
initSettings(dialog);
}
The initSettings method of the MainActivity class in this case will look like this:
// Определяем SeekBar и привязываем к нему дельты настроек
SeekBar sb_sense = (SeekBar)dialog.findViewById(R.id.seekSense);
SeekBar sb_vol = (SeekBar)dialog.findViewById(R.id.seekVol);
// Задаем этим SeekBar текущие значения настроек
sb_sense.setProgress(sense);
sb_vol.setProgress(volume);
Well, then process your objects as you please.
A small summary
1) AlertDialog is suitable for most purposes of dialogs
2) AlertDialog can take the form of layout with any objects
3) It is much better to use a separate class for dialogs and use AlertDialog.show ()
4) Custom layout objects are processed in the activity that caused the dialog
In the next Part of this article will talk about DialogFragment, which has been included in the Android SDK since 3.0 Honeycomb. I hope this article helps beginners and not so much in their quests to conquer Google Play.
PS
This is my first article for Habr, so I accept any constructive criticism. Thanks in advance.