5.10. Диалоговые окна, RadioButton и RadioGroup

5.10. Диалоговые окна, RadioButton и RadioGroup

Для создания диалоговых / модальных окон служит класс DialogFragment. Как уже поняли название класса подразумевает использование одного фрагмента в нескольких местах, поэтому и название заканчивается на Fragment.

Для ознакомления с диалоговыми / модальными окнами создайте проект с макетом Empty Activity. Добавьте класс, нажав правой кнопкой мыши на папку с название пакета, назовите класс MyDialog и в поле Superclass напишите  DialogFragment и если система предложит названия классов выберите androidx.fragment.app или же в поле Superclass сразу напишите androidx.fragment.app.DialogFragment.

В папку layout добавьте новый файл макета с названием dialog_layout и как корневой элемент укажите LinearLayout.

Откройте файл dialog_layout.xml и напишите следующий код:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <RadioGroup
        android:id="@+id/group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/v1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Variant 1" />

        <RadioButton
            android:id="@+id/v2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Variant 2" />

        <RadioButton
            android:id="@+id/v3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Variant 3" />
    </RadioGroup>
</LinearLayout>

Откройте файл activity_main.xml и напишите следующий код:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textColor="#000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/opendialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Open Dialog"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/hello" />
</androidx.constraintlayout.widget.ConstraintLayout>

Откройте файл res/values/colors.xml, в этом файле есть три значения для цвета, которые используются системой. Измените значения цветов как показано ниже:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3fb559</color>
    <color name="colorPrimaryDark">#309f57</color>
    <color name="colorAccent">#008600</color>
</resources>

Код файла MainActivity.java измените следующим образом:

public class MainActivity extends AppCompatActivity {
    Button openDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        openDialog = findViewById(R.id.opendialog);
        openDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Объявление и инициализация нового экземпляра диалога
                MyDialog dialog = new MyDialog();
                // Показать диалоговое окно
                dialog.show(getSupportFragmentManager(), "MyDialog");
            }
        });
    }
}

Код файла MyDialog.java измените на нижеследующий:

public class MyDialog extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Объявить и инициализировать экземпляр класса AlertDialog.Builder с передачей контекста конструктору
        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        // Установить заголовок диалогового окна
        alert.setMessage("Choose something");
        // Эта функция делает диалоговое окно не закрываемым по нажатию на кнопку назад или вне диаологового окна
        setCancelable(false);
        // Получить экземпляр класса LayoutInflater
        LayoutInflater inflater = getActivity().getLayoutInflater();
        // Присвоить полученный макет локальной переменной экземпляру класса View
        final View v = inflater.inflate(R.layout.dialog_layout, null, false);
        // Установить полученный макет в качестве макета диалогового окна
        alert.setView(v);
        // В файле макета dialog_layout.xml есть RadioGroup который содержит 3 RadioButton. Через RadioGroup получить информацию о выбранном RadioButton легче, потому что в данном случае обработчик изменения выбора подключается только к RadioGroup
        RadioGroup group = v.findViewById(R.id.group);
        // Подключить обработчик при изменении выбранного элемента внутри RadioGroup
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // Получить id выбранной кнопки и по id получить ссылку на выбранную радио кнопку
                RadioButton rb = v.findViewById(group.getCheckedRadioButtonId());
                // Показать сообщение с текстом и id выбранной кнопки
                Toast.makeText(getContext(), "Выбрана кнопка " + rb.getText() + checkedId, Toast.LENGTH_SHORT).show();
            }
        });
        // Устанавливает кнопку подтверждения и обработчик события клик для кнопки
        alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                Toast.makeText(getContext(), "Positive button clicked", Toast.LENGTH_SHORT).show();
                // Закрыть диалоговое окно функцией dismiss();
                dismiss();
            }
        });
        // Устанавливает кнопку отклонения и обработчик события клик для кнопки
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

           @Override
    public void onClick(DialogInterface dialog, int which) {
             dismiss();
     }
    });
        // Вернуть экземпляр диалогового окна для показа
        return alert.create();
    }
}
Запустите и протестируйте результат.