Okna

Wypróbuj sposób tworzenia wiadomości
Jetpack Compose to zalecany zestaw narzędzi UI na Androida. Dowiedz się, jak dodawać komponenty w oknie tworzenia wiadomości

Okno to małe okno, które zachęca użytkownika do podjęcia decyzji lub wpisania dodatkowych informacji. Okno nie wypełnia ekranu i zwykle jest używane w przypadku zdarzeń modalnych, które wymagają od użytkownika podjęcia działania przed kontynuacją.

Obraz przedstawiający podstawowe okno
Rysunek 1. Podstawowe okno.

Klasa Dialog jest klasą bazową dla okien dialogowych, ale nie twórz bezpośrednio instancji Dialog. Zamiast tego użyj jednej z tych podklas:

AlertDialog
Okno, które może wyświetlać tytuł, maksymalnie 3 przyciski, listę elementów do wyboru lub układ niestandardowy.
DatePickerDialog lub TimePickerDialog
Okno ze wstępnie zdefiniowanym interfejsem, które pozwala użytkownikowi wybrać datę lub godzinę.

Określają one styl i strukturę okna. Potrzebujesz też elementu DialogFragment jako kontenera okna. Klasa DialogFragment udostępnia wszystkie opcje potrzebne do utworzenia okna dialogowego i zarządzania jego wyglądem, zamiast wywoływania metod w obiekcie Dialog.

Zarządzanie oknem za pomocą DialogFragment pozwala prawidłowo obsługiwać zdarzenia cyklu życia, np. gdy użytkownik kliknie przycisk Wstecz lub obróci ekran. Klasa DialogFragment pozwala też wykorzystać interfejs okna dialogowego jako elementu możliwego do umieszczenia w większym interfejsie (tak jak w przypadku tradycyjnego Fragment), na przykład gdy interfejs okna ma wyglądać inaczej na dużych i małych ekranach.

Sekcje poniżej pokazują, jak używać właściwości DialogFragment w połączeniu z obiektem AlertDialog. Jeśli chcesz utworzyć selektor daty lub godziny, przeczytaj artykuł Dodawanie selektora daty lub godziny do aplikacji.

Tworzenie fragmentu okna dialogowego

Możesz tworzyć różne projekty okien, w tym układy niestandardowe i te opisane w oknach Material Design, przez rozszerzenie DialogFragment i utworzenie elementu AlertDialog w metodzie wywołania zwrotnego onCreateDialog().

Oto na przykład podstawowy obiekt AlertDialog zarządzany w ramach DialogFragment:

Kotlin

class StartGameDialogFragment : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            // Use the Builder class for convenient dialog construction.
            val builder = AlertDialog.Builder(it)
            builder.setMessage("Start game")
                .setPositiveButton("Start") { dialog, id ->
                    // START THE GAME!
                }
                .setNegativeButton("Cancel") { dialog, id ->
                    // User cancelled the dialog.
                }
            // Create the AlertDialog object and return it.
            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }
}

class OldXmlActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_old_xml)

        StartGameDialogFragment().show(supportFragmentManager, "GAME_DIALOG")
    }
}

Java

public class StartGameDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction.
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(R.string.dialog_start_game)
               .setPositiveButton(R.string.start, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // START THE GAME!
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // User cancels the dialog.
                   }
               });
        // Create the AlertDialog object and return it.
        return builder.create();
    }
}
// ...

StartGameDialogFragment().show(supportFragmentManager, "GAME_DIALOG");

Gdy utworzysz instancję tej klasy i wywołasz w niej właściwość show(), okno dialogowe wyświetli się, jak pokazano na rysunku poniżej.

Obraz przedstawiający podstawowe okno z 2 przyciskami poleceń
Rysunek 2. Okno z komunikatem i 2 przyciskami poleceń.

W następnej sekcji znajdziesz więcej informacji o używaniu AlertDialog.Builderinterfejsów API do tworzenia okna dialogowego.

W zależności od tego, jak skomplikowany jest okno, w DialogFragment możesz zaimplementować różne inne metody wywołania zwrotnego, w tym wszystkie podstawowe metody cyklu życia fragmentu.

Tworzenie okna alertu

Klasa AlertDialog umożliwia tworzenie różnych projektów okien dialogowych i często jest jedyną klasą, której potrzebujesz. Jak widać na ilustracji poniżej, okno dialogowe alertu wyróżnia 3 regiony:

  • Tytuł: ta wartość jest opcjonalna i używana tylko wtedy, gdy obszar treści jest wypełniany przez szczegółową wiadomość, listę lub układ niestandardowy. Jeśli chcesz stworzyć prostą wiadomość lub pytanie, nie potrzebujesz tytułu.
  • Obszar treści: może wyświetlać wiadomość, listę lub inny niestandardowy układ.
  • Przyciski działań: w oknie może się znajdować maksymalnie 3 przyciski poleceń.

Klasa AlertDialog.Builder udostępnia interfejsy API, które pozwalają utworzyć obiekt AlertDialog z tego typu zawartością, w tym z niestandardowym układem.

Aby utworzyć AlertDialog:

Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setMessage("I am the message")
    .setTitle("I am the title")

val dialog: AlertDialog = builder.create()
dialog.show()

Java

// 1. Instantiate an AlertDialog.Builder with its constructor.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

// 2. Chain together various setter methods to set the dialog characteristics.
builder.setMessage(R.string.dialog_message)
       .setTitle(R.string.dialog_title);

// 3. Get the AlertDialog.
AlertDialog dialog = builder.create();

Poprzedni fragment kodu generuje takie okno:

Obraz przedstawiający okno z tytułem, obszarem treści i 2 przyciskami polecenia.
Rysunek 3. Układ podstawowego okna alertu.

Dodaj przyciski

Aby dodać przyciski poleceń, takie jak te na rys. 2, wywołaj metody setPositiveButton() i setNegativeButton():

Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setMessage("I am the message")
    .setTitle("I am the title")
    .setPositiveButton("Positive") { dialog, which ->
        // Do something.
    }
    .setNegativeButton("Negative") { dialog, which ->
        // Do something else.
    }

val dialog: AlertDialog = builder.create()
dialog.show()

Java

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Add the buttons.
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // User taps OK button.
           }
       });
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // User cancels the dialog.
           }
       });
// Set other dialog properties.
...

// Create the AlertDialog.
AlertDialog dialog = builder.create();

Metody set...Button() wymagają tytułu przycisku (podanego przez zasób w postaci ciągu znaków) oraz elementu DialogInterface.OnClickListener określającego działanie, jakie ma zostać wykonane po kliknięciu przycisku przez użytkownika.

Dostępne są 3 przyciski działań, które możesz dodać:

  • Pozytywny: ten atrybut umożliwia zaakceptowanie działania i kontynuowanie jego wykonywania (działanie „OK”).
  • Wykluczające: służy do anulowania działania.
  • Nie mam zdania: użyj tej opcji, gdy użytkownik może nie chcieć wykonywać działania, ale nie musi go anulować. Znajduje się on między przyciskami plusa i minusa. Może to być na przykład „Przypomnij mi później”.

Do elementu AlertDialog możesz dodać tylko 1 przycisk każdego typu. Nie możesz na przykład mieć więcej niż 1 przycisku „dodatniego”.

Poprzedni fragment kodu zawiera okno dialogowe alertu podobne do tego:

Obraz przedstawiający okno alertu z tytułem, komunikatem i 2 przyciskami polecenia.
Rysunek 4. Okno alertu z tytułem, komunikatem i 2 przyciskami polecenia.

Dodaj listę

W interfejsach API AlertDialog dostępne są 3 rodzaje list:

  • Tradycyjna lista jednokrotnego wyboru.
  • stała lista jednokrotnego wyboru (przyciski).
  • stała lista jednokrotnego wyboru (pola wyboru),

Aby utworzyć listę jednokrotnego wyboru, taką jak ta na ilustracji 5, użyj metody setItems():


Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setTitle("I am the title")
    .setPositiveButton("Positive") { dialog, which ->
        // Do something.
    }
    .setNegativeButton("Negative") { dialog, which ->
        // Do something else.
    }
    .setItems(arrayOf("Item One", "Item Two", "Item Three")) { dialog, which ->
        // Do something on item tapped.
    }

val dialog: AlertDialog = builder.create()
dialog.show()

Java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.pick_color)
           .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
               // The 'which' argument contains the index position of the selected item.
           }
    });
    return builder.create();
}

Ten fragment kodu generuje okno podobne do tego:

Obraz przedstawiający okno z tytułem i listą.
Rysunek 5. Okno z tytułem i listą.

Lista jest widoczna w obszarze treści okna, więc w oknie nie można wyświetlić jednocześnie komunikatu i listy. Ustaw tytuł okna z elementem setTitle(). Aby określić elementy listy, wywołaj setItems(), przekazując tablicę. Możesz też określić listę za pomocą właściwości setAdapter(). Dzięki temu możesz utworzyć kopię zapasową listy z danymi dynamicznymi – np. z bazy danych – przy użyciu wywołania ListAdapter.

Jeśli przywracasz listę za pomocą elementu ListAdapter, zawsze używaj Loader, aby treść wczytywała się asynchronicznie. Zostało to szczegółowo opisane w sekcjach Tworzenie układów za pomocą adaptera i Wczytywanie.

dodać stałą listę jednokrotnego lub wielokrotnego wyboru,

Aby dodać listę produktów jednokrotnego wyboru (pola wyboru) lub elementów jednokrotnego wyboru (przyciski), użyj odpowiednio metody setMultiChoiceItems() lub setSingleChoiceItems().

Możesz na przykład utworzyć listę jednokrotnego wyboru, taką jak widoczna na rys. 6, i zapisać w niej wybrane elementy w elemencie ArrayList:

Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setTitle("I am the title")
    .setPositiveButton("Positive") { dialog, which ->
        // Do something.
    }
    .setNegativeButton("Negative") { dialog, which ->
        // Do something else.
    }
    .setMultiChoiceItems(
        arrayOf("Item One", "Item Two", "Item Three"), null) { dialog, which, isChecked ->
        // Do something.
    }

val dialog: AlertDialog = builder.create()
dialog.show()

Java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    selectedItems = new ArrayList();  // Where we track the selected items
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Set the dialog title.
    builder.setTitle(R.string.pick_toppings)
    // Specify the list array, the items to be selected by default (null for
    // none), and the listener through which to receive callbacks when items
    // are selected.
           .setMultiChoiceItems(R.array.toppings, null,
                      new DialogInterface.OnMultiChoiceClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which,
                       boolean isChecked) {
                   if (isChecked) {
                       // If the user checks the item, add it to the selected
                       // items.
                       selectedItems.add(which);
                   } else if (selectedItems.contains(which)) {
                       // If the item is already in the array, remove it.
                       selectedItems.remove(which);
                   }
               }
           })
    // Set the action buttons
           .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   // User taps OK, so save the selectedItems results
                   // somewhere or return them to the component that opens the
                   // dialog.
                   ...
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   ...
               }
           });

    return builder.create();
}
Obraz przedstawiający okno z listą produktów wielokrotnego wyboru.
Rysunek 6. Lista produktów wielokrotnego wyboru.

Okno alertu jednokrotnego wyboru może wyglądać tak:

Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setTitle("I am the title")
    .setPositiveButton("Positive") { dialog, which ->
        // Do something.
    }
    .setNegativeButton("Negative") { dialog, which ->
        // Do something else.
    }
    .setSingleChoiceItems(
        arrayOf("Item One", "Item Two", "Item Three"), 0
    ) { dialog, which ->
        // Do something.
    }

val dialog: AlertDialog = builder.create()
dialog.show()

Java

        String[] choices = {"Item One", "Item Two", "Item Three"};
        
        AlertDialog.Builder builder = AlertDialog.Builder(context);
        builder
                .setTitle("I am the title")
                .setPositiveButton("Positive", (dialog, which) -> {

                })
                .setNegativeButton("Negative", (dialog, which) -> {

                })
                .setSingleChoiceItems(choices, 0, (dialog, which) -> {

                });

        AlertDialog dialog = builder.create();
        dialog.show();

W rezultacie uzyskasz taki przykład:

Obraz przedstawiający okno z listą produktów jednokrotnego wyboru.
Rysunek 7. Lista produktów jednokrotnego wyboru.

Tworzenie układu niestandardowego

Jeśli chcesz, aby w oknie dialogowym miał układ niestandardowy, utwórz układ i dodaj go do elementu AlertDialog, wywołując metodę setView() w obiekcie AlertDialog.Builder.

Obraz przedstawiający niestandardowy układ okna dialogowego.
Rysunek 8. Niestandardowy układ okna dialogowego.

Domyślnie układ niestandardowy wypełnia okno, ale nadal możesz używać metod AlertDialog.Builder, aby dodawać przyciski i tytuł.

Oto na przykład plik układu dla poprzedniego układu niestandardowego okna:

res/layout/dialog_signin.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@drawable/header_logo"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:scaleType="center"
        android:background="#FFFFBB33"
        android:contentDescription="@string/app_name" />
    <EditText
        android:id="@+id/username"
        android:inputType="textEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="4dp"
        android:hint="@string/username" />
    <EditText
        android:id="@+id/password"
        android:inputType="textPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:fontFamily="sans-serif"
        android:hint="@string/password"/>
</LinearLayout>

Aby powiększyć układ w elemencie DialogFragment, użyj polecenia LayoutInflater getLayoutInflater() i wywołaj inflate(). Pierwszy parametr to identyfikator zasobu układu, a drugi – widok nadrzędny układu. Następnie możesz wywołać setView(), aby umieścić układ w oknie. Widać to w przykładzie poniżej.

Kotlin

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    return activity?.let {
        val builder = AlertDialog.Builder(it)
        // Get the layout inflater.
        val inflater = requireActivity().layoutInflater;

        // Inflate and set the layout for the dialog.
        // Pass null as the parent view because it's going in the dialog
        // layout.
        builder.setView(inflater.inflate(R.layout.dialog_signin, null))
                // Add action buttons.
                .setPositiveButton(R.string.signin,
                        DialogInterface.OnClickListener { dialog, id ->
                            // Sign in the user.
                        })
                .setNegativeButton(R.string.cancel,
                        DialogInterface.OnClickListener { dialog, id ->
                            getDialog().cancel()
                        })
        builder.create()
    } ?: throw IllegalStateException("Activity cannot be null")
}

Java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater.
    LayoutInflater inflater = requireActivity().getLayoutInflater();

    // Inflate and set the layout for the dialog.
    // Pass null as the parent view because it's going in the dialog layout.
    builder.setView(inflater.inflate(R.layout.dialog_signin, null))
    // Add action buttons
           .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   // Sign in the user.
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   LoginDialogFragment.this.getDialog().cancel();
               }
           });
    return builder.create();
}

Jeśli chcesz utworzyć okno niestandardowe, możesz wyświetlić okno Activity w formie okna, zamiast korzystać z interfejsów API Dialog. Utwórz aktywność i ustaw jej motyw na Theme.Holo.Dialog w elemencie manifestu <activity>:

<activity android:theme="@android:style/Theme.Holo.Dialog" >

Aktywność wyświetla się teraz w oknie dialogowym, a nie w trybie pełnoekranowym.

Przekazywanie zdarzeń z powrotem do hosta okna

Gdy użytkownik kliknie jeden z przycisków poleceń w oknie lub wybierze element z listy, DialogFragment może samodzielnie wykonać niezbędną czynność, ale często chcesz dostarczać zdarzenie do działania lub fragmentu, który otwiera okno. Aby to zrobić, zdefiniuj interfejs z metodą dla każdego typu zdarzenia kliknięcia. Następnie zaimplementuj ten interfejs w komponencie hosta, który odbiera zdarzenia działań z okna.

Oto na przykład obiekt DialogFragment określający interfejs, za pomocą którego dostarcza zdarzenia z powrotem do aktywności hosta:

Kotlin

class NoticeDialogFragment : DialogFragment() {
    // Use this instance of the interface to deliver action events.
    internal lateinit var listener: NoticeDialogListener

    // The activity that creates an instance of this dialog fragment must
    // implement this interface to receive event callbacks. Each method passes
    // the DialogFragment in case the host needs to query it.
    interface NoticeDialogListener {
        fun onDialogPositiveClick(dialog: DialogFragment)
        fun onDialogNegativeClick(dialog: DialogFragment)
    }

    // Override the Fragment.onAttach() method to instantiate the
    // NoticeDialogListener.
    override fun onAttach(context: Context) {
        super.onAttach(context)
        // Verify that the host activity implements the callback interface.
        try {
            // Instantiate the NoticeDialogListener so you can send events to
            // the host.
            listener = context as NoticeDialogListener
        } catch (e: ClassCastException) {
            // The activity doesn't implement the interface. Throw exception.
            throw ClassCastException((context.toString() +
                    " must implement NoticeDialogListener"))
        }
    }
}

Java

public class NoticeDialogFragment extends DialogFragment {

    // The activity that creates an instance of this dialog fragment must
    // implement this interface to receive event callbacks. Each method passes
    // the DialogFragment in case the host needs to query it.
    public interface NoticeDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }

    // Use this instance of the interface to deliver action events.
    NoticeDialogListener listener;

    // Override the Fragment.onAttach() method to instantiate the
    // NoticeDialogListener.
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // Verify that the host activity implements the callback interface.
        try {
            // Instantiate the NoticeDialogListener so you can send events to
            // the host.
            listener = (NoticeDialogListener) context;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface. Throw exception.
            throw new ClassCastException(activity.toString()
                    + " must implement NoticeDialogListener");
        }
    }
    ...
}

Działanie hostujące okno dialogowe tworzy instancję okna z konstruktorem fragmentu okna i odbiera zdarzenia z okna za pomocą implementacji interfejsu NoticeDialogListener:

Kotlin

class MainActivity : FragmentActivity(),
        NoticeDialogFragment.NoticeDialogListener {

    fun showNoticeDialog() {
        // Create an instance of the dialog fragment and show it.
        val dialog = NoticeDialogFragment()
        dialog.show(supportFragmentManager, "NoticeDialogFragment")
    }

    // The dialog fragment receives a reference to this Activity through the
    // Fragment.onAttach() callback, which it uses to call the following
    // methods defined by the NoticeDialogFragment.NoticeDialogListener
    // interface.
    override fun onDialogPositiveClick(dialog: DialogFragment) {
        // User taps the dialog's positive button.
    }

    override fun onDialogNegativeClick(dialog: DialogFragment) {
        // User taps the dialog's negative button.
    }
}

Java

public class MainActivity extends FragmentActivity
                          implements NoticeDialogFragment.NoticeDialogListener{
    ...
    public void showNoticeDialog() {
        // Create an instance of the dialog fragment and show it.
        DialogFragment dialog = new NoticeDialogFragment();
        dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
    }

    // The dialog fragment receives a reference to this Activity through the
    // Fragment.onAttach() callback, which it uses to call the following
    // methods defined by the NoticeDialogFragment.NoticeDialogListener
    // interface.
    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        // User taps the dialog's positive button.
        ...
    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {
        // User taps the dialog's negative button.
        ...
    }
}

Ponieważ działanie hosta implementuje funkcję NoticeDialogListener, która jest egzekwowana przez metodę wywołania zwrotnego onAttach() widoczną w poprzednim przykładzie, fragment okna może używać metod wywołania zwrotnego interfejsu, aby dostarczać zdarzenia kliknięcia do aktywności:

Kotlin

    override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
        return activity?.let {
            // Build the dialog and set up the button click handlers.
            val builder = AlertDialog.Builder(it)

            builder.setMessage(R.string.dialog_start_game)
                    .setPositiveButton(R.string.start,
                            DialogInterface.OnClickListener { dialog, id ->
                                // Send the positive button event back to the
                                // host activity.
                                listener.onDialogPositiveClick(this)
                            })
                    .setNegativeButton(R.string.cancel,
                            DialogInterface.OnClickListener { dialog, id ->
                                // Send the negative button event back to the
                                // host activity.
                                listener.onDialogNegativeClick(this)
                            })

            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }

Java

public class NoticeDialogFragment extends DialogFragment {
    ...
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Build the dialog and set up the button click handlers.
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(R.string.dialog_start_game)
               .setPositiveButton(R.string.start, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // Send the positive button event back to the host activity.
                       listener.onDialogPositiveClick(NoticeDialogFragment.this);
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // Send the negative button event back to the host activity.
                       listener.onDialogNegativeClick(NoticeDialogFragment.this);
                   }
               });
        return builder.create();
    }
}

Pokaż okno

Jeśli chcesz wyświetlić okno dialogowe, utwórz wystąpienie DialogFragment i wywołaj show(), przekazując parametr FragmentManager i nazwę tagu odpowiadającego fragmentowi okna.

FragmentManager możesz uzyskać, dzwoniąc pod numer getSupportFragmentManager() z operatora FragmentActivity lub dzwoniąc do: getParentFragmentManager() z numeru Fragment. Oto przykład:

Kotlin

fun confirmStartGame() {
    val newFragment = StartGameDialogFragment()
    newFragment.show(supportFragmentManager, "game")
}

Java

public void confirmStartGame() {
    DialogFragment newFragment = new StartGameDialogFragment();
    newFragment.show(getSupportFragmentManager(), "game");
}

Drugi argument ("game") to unikalna nazwa tagu, której system używa do zapisywania i przywracania stanu fragmentów, gdy jest to konieczne. Tag umożliwia też uzyskanie uchwytu fragmentu przez wywołanie findFragmentByTag().

Pokaż okno dialogowe na pełnym ekranie lub jako fragment osadzony

W niektórych sytuacjach fragment interfejsu może się wyświetlać jako okno, a w innych – jako okno pełnoekranowe lub fragmenty umieszczone na ekranie. Może też wyglądać różnie w zależności od rozmiaru ekranu urządzenia. Klasa DialogFragment zapewnia elastyczność, ponieważ może działać jak umieszczany element Fragment.

W tym przypadku nie możesz jednak używać obiektów AlertDialog.Builder ani innych obiektów Dialog do utworzenia okna. Jeśli chcesz, aby element DialogFragment można było umieścić, zdefiniuj interfejs okna w układzie, a następnie wczytaj ten układ w wywołaniu zwrotnym onCreateView().

Oto przykład elementu DialogFragment, który może pojawić się jako okno lub fragment do umieszczenia, w układzie o nazwie purchase_items.xml:

Kotlin

class CustomDialogFragment : DialogFragment() {

    // The system calls this to get the DialogFragment's layout, regardless of
    // whether it's being displayed as a dialog or an embedded fragment.
    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        // Inflate the layout to use as a dialog or embedded fragment.
        return inflater.inflate(R.layout.purchase_items, container, false)
    }

    // The system calls this only when creating the layout in a dialog.
    override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
        // The only reason you might override this method when using
        // onCreateView() is to modify the dialog characteristics. For example,
        // the dialog includes a title by default, but your custom layout might
        // not need it. Here, you can remove the dialog title, but you must
        // call the superclass to get the Dialog.
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        return dialog
    }
}

Java

public class CustomDialogFragment extends DialogFragment {
    // The system calls this to get the DialogFragment's layout, regardless of
    // whether it's being displayed as a dialog or an embedded fragment.
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout to use as a dialog or embedded fragment.
        return inflater.inflate(R.layout.purchase_items, container, false);
    }

    // The system calls this only when creating the layout in a dialog.
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // The only reason you might override this method when using
        // onCreateView() is to modify the dialog characteristics. For example,
        // the dialog includes a title by default, but your custom layout might
        // not need it. Here, you can remove the dialog title, but you must
        // call the superclass to get the Dialog.
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }
}

Ten przykład określa, czy wyświetlić fragment jako okno, czy jako interfejs pełnoekranowy, w zależności od rozmiaru ekranu:

Kotlin

fun showDialog() {
    val fragmentManager = supportFragmentManager
    val newFragment = CustomDialogFragment()
    if (isLargeLayout) {
        // The device is using a large layout, so show the fragment as a
        // dialog.
        newFragment.show(fragmentManager, "dialog")
    } else {
        // The device is smaller, so show the fragment fullscreen.
        val transaction = fragmentManager.beginTransaction()
        // For a polished look, specify a transition animation.
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        // To make it fullscreen, use the 'content' root view as the container
        // for the fragment, which is always the root view for the activity.
        transaction
                .add(android.R.id.content, newFragment)
                .addToBackStack(null)
                .commit()
    }
}

Java

public void showDialog() {
    FragmentManager fragmentManager = getSupportFragmentManager();
    CustomDialogFragment newFragment = new CustomDialogFragment();

    if (isLargeLayout) {
        // The device is using a large layout, so show the fragment as a
        // dialog.
        newFragment.show(fragmentManager, "dialog");
    } else {
        // The device is smaller, so show the fragment fullscreen.
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // For a polished look, specify a transition animation.
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        // To make it fullscreen, use the 'content' root view as the container
        // for the fragment, which is always the root view for the activity.
        transaction.add(android.R.id.content, newFragment)
                   .addToBackStack(null).commit();
    }
}

Więcej informacji o wykonywaniu transakcji z fragmentami znajdziesz w sekcji Fragmenty.

W tym przykładzie wartość logiczna mIsLargeLayout określa, czy bieżące urządzenie musi używać dużego układu aplikacji, więc pokazuje ten fragment jako okno dialogowe, a nie pełny ekran. Najlepszym sposobem na ustawienie tego rodzaju wartości logicznej jest zadeklarowanie wartości zasobu logicznego z wartością zasobu alternatywnego dla różnych rozmiarów ekranu. Oto 2 wersje zasobu logicznego dla różnych rozmiarów ekranu:

res/values/bools.xml

<!-- Default boolean values -->
<resources>
    <bool name="large_layout">false</bool>
</resources>

res/values-large/bools.xml

<!-- Large screen boolean values -->
<resources>
    <bool name="large_layout">true</bool>
</resources>

Następnie możesz zainicjować wartość mIsLargeLayout podczas metody onCreate() aktywności, jak pokazano w tym przykładzie:

Kotlin

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    isLargeLayout = resources.getBoolean(R.bool.large_layout)
}

Java

boolean isLargeLayout;

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

    isLargeLayout = getResources().getBoolean(R.bool.large_layout);
}

Pokazuj aktywność jako okno na dużych ekranach

Zamiast wyświetlać okno jako interfejs pełnoekranowy na małych ekranach, ten sam efekt możesz uzyskać, wyświetlając Activity jako okno na dużych ekranach. Wybór metody zależy od projektu aplikacji. Jeśli aplikacja jest przeznaczona na małe ekrany, warto pokazać działanie w formie okna z działaniami, a chcesz poprawić komfort korzystania z niej na tabletach, pokazując krótkotrwałą aktywność w oknie dialogowym.

Aby wyświetlić działanie jako okno tylko na dużych ekranach, zastosuj motyw Theme.Holo.DialogWhenLarge do elementu manifestu <activity>:

<activity android:theme="@android:style/Theme.Holo.DialogWhenLarge" >

Więcej informacji o stylizowaniu działań za pomocą motywów znajdziesz w artykule Style i motywy.

Zamykanie okna

Gdy użytkownik kliknie przycisk polecenia utworzony przy użyciu AlertDialog.Builder, system zamknie to okno.

Poza tym, gdy użytkownik kliknie element na liście, system zamyka okno, chyba że na liście znajdują się przyciski lub pola wyboru. Możesz też ręcznie zamknąć to okno, wywołując metodę dismiss() na urządzeniu DialogFragment.

Jeśli po zamknięciu okna musisz wykonać określone działania, możesz zaimplementować metodę onDismiss() w interfejsie DialogFragment.

Możesz też anulować okno. Jest to specjalne zdarzenie, które oznacza, że użytkownik opuszcza okno, nie wykonując zadania. Dzieje się tak, gdy użytkownik kliknie przycisk Wstecz lub ekran poza obszarem okna lub wywołasz polecenie cancel() w Dialog, np. w odpowiedzi na przycisk „Anuluj” w oknie.

Jak pokazano w poprzednim przykładzie, możesz odpowiedzieć na zdarzenie anulowania, implementując onCancel() w klasie DialogFragment.