תיבות דו-שיח

רוצה לנסות את שיטת הכתיבה?
'Jetpack פיתוח נייטיב' היא ערכת הכלים המומלצת לממשק המשתמש ל-Android. מידע על הוספת רכיבים לכתיבה.

תיבת דו-שיח היא חלון קטן שבו המשתמש מתבקש ליצור או להזין מידע נוסף. לא מופיעה תיבת דו-שיח במסך משמש בדרך כלל לאירועים מודאליים שמחייבים את המשתמשים לבצע פעולה לפני הם יוכלו להמשיך.

תמונה שמוצגת בה תיבת דו-שיח בסיסית
איור 1. תיבת דו-שיח בסיסית.

Dialog המחלקה היא מחלקה הבסיסית של תיבות דו-שיח, אבל לא יוצרת מופע של Dialog ישירות. במקום זאת, משתמשים באחת ממחלקות המשנה הבאות:

AlertDialog
תיבת דו-שיח שבה אפשר להציג כותרת, עד שלושה לחצנים, ורשימה של פריטים שאפשר לבחור פריטים או פריסה מותאמת אישית.
DatePickerDialog או TimePickerDialog
תיבת דו-שיח עם ממשק משתמש מוגדר מראש שמאפשר למשתמש לבחור תאריך או בזמן האימון.

המחלקות האלה מגדירות את הסגנון והמבנה של תיבת הדו-שיח. צריך גם A DialogFragment בתור מאגר לתיבת הדו-שיח. הכיתה DialogFragment מספקת את כל הפקדים הדרושים ליצירת תיבת דו-שיח ולניהול המראה שלה, במקום לשלוח קריאה ל-methods באובייקט Dialog.

ניהול תיבת הדו-שיח מתבצע כמו שצריך באמצעות DialogFragment טיפול באירועים במחזור החיים, כמו הקשה על לחצן 'הקודם' או סיבוב. במסך. המחלקה DialogFragment מאפשרת גם לעשות שימוש חוזר כרכיב ניתן להטמעה בממשק משתמש גדול יותר – בדיוק כמו מסורתי Fragment - כגון למשל, כשרוצים שממשק המשתמש של תיבת הדו-שיח ייראה שונה בניידים מסכים.

הקטעים הבאים במסמך הזה מתארים איך להשתמש DialogFragment בשילוב עם AlertDialog לאובייקט. כדי ליצור חלונית לבחירת תאריך או שעה, אפשר לקרוא הוספת בוררים אל app.

יצירת מקטע של תיבת דו-שיח

אפשר ליצור מגוון רחב של עיצובים של תיבות דו-שיח, כולל עיצובים מותאמים אישית והפריסות שמתוארות עיצוב חומר תיבות דו-שיח – על ידי הרחבה של DialogFragment ויצירת תיבת דו-שיח AlertDialog ב- onCreateDialog() שיטת קריאה חוזרת.

לדוגמה, הנה AlertDialog בסיסי שמנוהל בתוך 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");

כשיוצרים מופע של הכיתה הזו וקוראים show() על האובייקט, תיבת הדו-שיח תופיע כפי שמוצג באיור הבא.

תמונה שמוצגת בה תיבת דו-שיח בסיסית עם שני לחצני פעולה
איור 2. תיבת דו-שיח עם הודעה ושתיים לחצני פעולה.

בקטע הבא מתוארים פרטים נוספים על השימוש AlertDialog.Builder ממשקי API ליצירת תיבת הדו-שיח.

בהתאם למורכבות תיבת הדו-שיח, אפשר ליישם מגוון של שיטות אחרות להתקשרות חזרה בDialogFragment, כולל כל שיטות בסיסיות של מחזור חיים של קטעים.

יצירת תיבת דו-שיח של התראה

המחלקה AlertDialog מאפשרת ליצור מגוון של תיבות דו-שיח ובדרך כלל המחלקה היחידה שדרושה לכם היא תיבת דו-שיח. כפי שמוצג כאן, כלומר, יש שלושה אזורים בתיבת הדו-שיח של ההתראה:

  • כותרת: זהו שדה אופציונלי ומשתמשים בו רק אם אזור התוכן הוא כולל הודעה מפורטת, רשימה או פריסה מותאמת אישית. אם צריך כתוב הודעה פשוטה או שאלה פשוטה, אין צורך בכותרת.
  • אזור תוכן: באזור הזה ניתן להציג הודעה, רשימה או אזור אחר בהתאמה אישית הפריסה שלו.
  • לחצני פעולה: יכולים לכלול עד שלושה לחצני פעולה בכל

המחלקה AlertDialog.Builder מספקת ממשקי API שמאפשרים ליצור AlertDialog עם סוגי תוכן כאלה, כולל תג התאמה אישית הפריסה שלו.

כדי ליצור 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();

קטע הקוד הקודם יוצר תיבת דו-שיח זו:

תמונה שמוצגת בה תיבת דו-שיח עם כותרת, אזור תוכן ושני לחצני פעולה.
איור 3. הפריסה של התראה בסיסית

הוספת לחצנים

כדי להוסיף לחצני פעולה כמו אלה שמופיעים בתמונה מספר 2, מפעילים setPositiveButton() וגם 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();

ל-methods set...Button() נדרשת כותרת עבור לחצן – מסופק על ידי משאב מחרוזות — וגם A DialogInterface.OnClickListener שמגדירה את הפעולה שצריך לבצע כשהמשתמש מקיש על הלחצן.

יש שלושה לחצני פעולה שאפשר להוסיף:

  • ערך חיובי: השתמשו באפשרות הזו כדי לקבל את הפעולה ולהמשיך עם הפעולה ( "אישור" ).
  • שלילי: משתמשים במאפיין הזה כדי לבטל את הפעולה.
  • ניטרלי: האפשרות הזו מתאימה אם המשתמש לא רוצה להמשיך בתהליך. פעולה, אבל לא בהכרח רוצה לבטל. היא מופיעה בין ולחצנים חיוביים ושליליים. לדוגמה, הפעולה יכולה להיות "אני רוצה לקבל תזכורת מאוחר יותר".

אפשר להוסיף לAlertDialog רק לחצן אחד מכל סוג. עבור למשל, אי אפשר לציין יותר ממדד 'חיובי' אחד לחצן.

בקטע הקוד הקודם מופיעה תיבת דו-שיח עם התראה כמו בדוגמה הבאה:

תמונה שמוצגת בה תיבת דו-שיח של התראה עם כותרת, הודעה ושני לחצני פעולה.
איור 4. תיבת דו-שיח של התראה עם כותרת. הודעה מסוימת, ושני לחצני פעולה.

הוספת רשימה

יש שלושה סוגי רשימות שזמינים במאפיין AlertDialog ממשקי API:

  • רשימה מסורתית של שאלה יחידה.
  • רשימה קבועה של בחירה יחידה (לחצני בחירה).
  • רשימה של שאלות אמריקאיות קבועות (תיבות סימון).

כדי ליצור רשימה של בחירה יחידה, כמו זו שמופיעה באיור 5, משתמשים setItems() method:


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();
}

קטע הקוד הזה יוצר תיבת דו-שיח כמו זו:

תמונה שמוצגת בה תיבת דו-שיח עם כותרת ורשימה.
איור 5. תיבת דו-שיח עם כותרת ורשימה.

מאחר שהרשימה מופיעה באזור התוכן של תיבת הדו-שיח, לא ניתן להציג את תיבת הדו-שיח. גם הודעה וגם רשימה. הגדרת כותרת לתיבת הדו-שיח עם setTitle() כדי לציין את הפריטים עבור הרשימה, קוראים לפונקציה setItems(), ומעבירים מערך. לחלופין, אפשר לציין רשימה באמצעות setAdapter() כך תוכל לגבות את הרשימה עם נתונים דינמיים - כמו מסד נתונים – באמצעות ListAdapter

אם מגבים את הרשימה באמצעות ListAdapter, צריך להשתמש תמיד Loader כך שהתוכן ייטען באופן אסינכרוני. מתואר עוד בנושא הזה יצירת פריסות עם מתאם, מטענים.

להוסיף רשימה של שאלות אמריקאיות קבועות או של שאלה אחת

כדי להוסיף רשימה של שאלות אמריקאיות (תיבות סימון) או של פריטים לבחירה אחת (לחצני בחירה), משתמשים בפקודה setMultiChoiceItems() או setSingleChoiceItems() שיטות, בהתאמה.

לדוגמה, כך תוכלו ליצור רשימה של שאלות אמריקאיות, כמו הרשימה שמוצגת בתרשים 6 ששומר את הפריטים שנבחרו 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();
}
תמונה שמוצגת בה תיבת דו-שיח שמכילה רשימה של פריטים עם שאלות אמריקאיות.
איור 6. רשימה של פריטים שיש להם שאלות אמריקאיות.

ייתכן שתוצג תיבת דו-שיח להתראות עם שאלה אחת, באופן הבא:

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();

כתוצאה מכך, מתקבלת הדוגמה הבאה:

תמונה שמוצגת בה תיבת דו-שיח שמכילה רשימה של פריטים עם בחירה יחידה.
איור 7. רשימה של פריטים לבחירה אחת.

יצירת פריסה מותאמת אישית

אם רוצים פריסה מותאמת אישית בתיבת דו-שיח, אפשר ליצור פריסה ולהוסיף אותה AlertDialog על ידי התקשרות setView() על האובייקט AlertDialog.Builder.

תמונה שמוצגת בה פריסה של תיבת דו-שיח בהתאמה אישית.
איור 8. פריסה של תיבת דו-שיח בהתאמה אישית.

כברירת מחדל, הפריסה המותאמת אישית ממלאת את חלון תיבת הדו-שיח, אבל עדיין ניתן להשתמש AlertDialog.Builder שיטות להוספת לחצנים וכותרת.

לדוגמה, זהו קובץ הפריסה לתיבת הדו-שיח המותאמת אישית הקודמת פריסה:

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>

כדי להגדיל את הפריסה ב-DialogFragment, LayoutInflater עם getLayoutInflater() ולהתקשר inflate() הפרמטר הראשון הוא מזהה המשאב של הפריסה והפרמטר השני הוא לתצוגת ההורה של הפריסה. לאחר מכן תוכלו להתקשר setView() כדי למקם את הפריסה בתיבת הדו-שיח. אפשר לראות זאת בדוגמה הבאה.

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();
}

אם ברצונך לפתוח תיבת דו-שיח בהתאמה אישית, אפשר להציג במקום זאת Activity בתור במקום להשתמש בממשקי ה-API של Dialog. יוצרים פעילות ו הגדרת העיצוב כ- Theme.Holo.Dialog ב <activity> רכיב מניפסט:

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

הפעילות תוצג עכשיו בחלון של תיבת דו-שיח במקום במסך מלא.

העברת האירועים בחזרה למארח של תיבת הדו-שיח

כשהמשתמש מקיש על אחד מלחצני הפעולה בתיבת הדו-שיח או בוחר פריט מהרשימה שלו, DialogFragment עשוי לבצע את הפעולה עצמה, אבל לעיתים קרובות רוצים להעביר את האירוע לפעילות או מקטע הפותח את תיבת הדו-שיח. כדי לעשות את זה, צריך להגדיר ממשק באמצעות method. לכל סוג של אירוע קליק. לאחר מכן מטמיעים את הממשק הרכיב שמקבל את אירועי הפעולה מתיבת הדו-שיח.

לדוגמה, הנה DialogFragment שמגדיר ממשק דרכה היא מחזירה את האירועים לפעילות של המארח:

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");
        }
    }
    ...
}

הפעילות המארחת את תיבת הדו-שיח יוצרת מופע של תיבת הדו-שיח עם של מקטע תיבת דו-שיח, ומקבל את האירועים של תיבת הדו-שיח באמצעות הטמעה של הממשק 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.
        ...
    }
}

מאחר שהפעילות המארחת מטמיעה את NoticeDialogListener – שנאכף על ידי onAttach() שיטת הקריאה החוזרת (callback) שמוצגת בדוגמה הקודמת - הקטע של תיבת הדו-שיח יכול להשתמש בשיטות קריאה חוזרת (callback) בממשק כדי להציג אירועי קליקים לפעילות:

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();
    }
}

הצגה של תיבת דו-שיח

כשרוצים להציג את תיבת הדו-שיח, יוצרים מופע של DialogFragment והתקשרות show(), להעביר את FragmentManager ושם תג למקטע של תיבת הדו-שיח.

אפשר לקבל את FragmentManager בטלפון getSupportFragmentManager() מ- FragmentActivity או בטלפון getParentFragmentManager() מ-Fragment. לדוגמה:

Kotlin

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

Java

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

הארגומנט השני, "game", הוא שם ייחודי של תג משתמשת כדי לשמור ולשחזר את מצב המקטע במקרה הצורך. התג גם מאפשר לקבל נקודת אחיזה למקטע באמצעות קריאה findFragmentByTag()

הצגה של תיבת דו-שיח במסך מלא או כמקטע מוטמע

ייתכן שתרצו שחלק מהעיצוב של ממשק המשתמש יופיע בתור תיבת דו-שיח וכקטע במסך מלא או כקטע מוטמע באחרים. אפשר גם רוצה שהתצוגה תהיה שונה בהתאם לגודל המסך של המכשיר. בכיתה DialogFragment יש גמישות לביצוע הפעולה הזו, כי הוא יכול להתנהג כמו Fragment שניתן להטמעה.

עם זאת, אי אפשר להשתמש ב-AlertDialog.Builder או באמצעי אחר Dialog אובייקטים כדי ליצור את תיבת הדו-שיח במקרה הזה. אם רוצים DialogFragment כדי שניתן יהיה להטמיע, מגדירים את ממשק המשתמש של תיבת הדו-שיח וטוענים את הפריסה onCreateView() קריאה חוזרת.

הנה DialogFragment לדוגמה שיכול להופיע בתיבת דו-שיח או שבר ניתן להטמעה, באמצעות פריסה בשם 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;
    }
}

הדוגמה הבאה קובעת אם להציג את המקטע בתיבת דו-שיח או ממשק משתמש במסך מלא, בהתאם לגודל המסך:

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();
    }
}

למידע נוסף על ביצוע טרנזקציות במקטעים, ראו: מקטעים.

בדוגמה זו, הערך הבוליאני mIsLargeLayout מציין אם המכשיר הנוכחי צריך להשתמש בעיצוב הפריסה הגדול של האפליקציה, ולכן יוצג שמקטעים בתור תיבת דו-שיח ולא כמסך מלא. הדרך הטובה ביותר להגדיר הערך הבוליאני הוא להצהיר משאב בוליאני עם ערך חלופה משאב לגדלים שונים של מסכים. לדוגמה, הנה שני גרסאות של משאב הבוליאני למסכים בגדלים שונים:

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>

לאחר מכן אפשר לאתחל את הערך של mIsLargeLayout במהלך של פעילות onCreate() כפי שאפשר לראות בדוגמה הבאה:

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);
}

הצגת פעילות כתיבת דו-שיח במסכים גדולים

במקום להציג תיבת דו-שיח כממשק משתמש במסך מלא במסכים קטנים, אפשר אותה תוצאה על ידי הצגת Activity בתור תיבת דו-שיח מסכים. הגישה שתבחרו תלויה בעיצוב האפליקציה, אבל תציגו הפעילות שלך בתור תיבת דו-שיח שימושית בדרך כלל כאשר האפליקציה מיועדת במסכים ואתם רוצים לשפר את החוויה בטאבלטים, פעילות לטווח קצר כתיבת דו-שיח.

כדי להציג פעילות כתיבת דו-שיח רק במסכים גדולים, צריך להחיל את Theme.Holo.DialogWhenLarge עיצוב לרכיב המניפסט <activity>:

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

למידע נוסף על עיצוב הפעילויות שלך באמצעות עיצובים, ראו סגנונות ועיצובים.

סגירה של תיבת דו-שיח

כשהמשתמש מקיש על לחצן פעולה שנוצר באמצעות AlertDialog.Builder, המערכת תסגור את תיבת הדו-שיח בשבילכם.

המערכת גם סוגרת את תיבת הדו-שיח כשהמשתמש מקיש על פריט בתיבת דו-שיח אלא אם הרשימה משתמשת בלחצני בחירה או בתיבות סימון. אחרת, אפשר כדי לסגור את תיבת הדו-שיח באופן ידני, צריך להתקשר dismiss() במכשיר DialogFragment שלך.

אם אתם צריכים לבצע פעולות מסוימות כשתיבת הדו-שיח נעלמת, אפשר: להטמיע את onDismiss() ב-DialogFragment.

אפשר גם לבטל תיבת דו-שיח. זהו אירוע מיוחד מציין שהמשתמש יצא מתיבת הדו-שיח בלי להשלים את המשימה. הזה מתרחשת אם המשתמש מקיש על לחצן 'הקודם' או מקיש על המסך מחוץ לתיבת הדו-שיח או אם קוראים במפורש cancel() ב-Dialog, למשל בתגובה ל'ביטול' בלחצן

כפי שאפשר לראות בדוגמה שלמעלה, אפשר להגיב לאירוע הביטול באמצעות בתהליך הטמעה onCancel() בכיתה DialogFragment שלך.