대화상자

Compose 방식 사용해 보기
Jetpack Compose는 Android에 권장되는 UI 도구 키트입니다. Compose에서 구성요소를 추가하는 방법을 알아보세요.
<ph type="x-smartling-placeholder"></ph> AlertDialog → 를 통해 개인정보처리방침을 정의할 수 있습니다.

대화상자는 사용자에게 작업을 수행하라는 메시지를 표시하는 작은 창입니다. 추가 정보를 입력할 수 있습니다. 대화상자가 화면을 채우지 않고 는 일반적으로 사용자가 작업을 완료해야 하는 모달 이벤트에 사용됩니다. 계속 진행할 수 있습니다

<ph type="x-smartling-placeholder">를 통해 개인정보처리방침을 정의할 수 있습니다. <ph type="x-smartling-placeholder">
</ph> <ph type="x-smartling-placeholder">기본 대화상자를 보여주는 이미지</ph> <ph type="x-smartling-placeholder">
</ph> 그림 1. 기본 대화상자

Dialog 클래스가 대화상자의 기본 클래스이지만 Dialog를 인스턴스화하지 않음 바로 그것입니다. 대신 다음 서브클래스 중 하나를 사용하세요.

AlertDialog
제목 한 개, 최대 3개의 버튼, 선택 가능한 맞춤 레이아웃으로 만들 수 있습니다.
DatePickerDialog 또는 TimePickerDialog
사용자가 날짜 또는 날짜를 선택할 수 있는 사전 정의된 UI가 있는 대화상자 있습니다.
를 통해 개인정보처리방침을 정의할 수 있습니다.
를 통해 개인정보처리방침을 정의할 수 있습니다. <ph type="x-smartling-placeholder">

이 클래스는 대화상자의 스타일과 구조를 정의합니다. 또한 a DialogFragment 대화상자의 컨테이너로 사용합니다 DialogFragment 클래스는 대화상자를 만들고 모양을 관리하는 데 필요한 모든 컨트롤과 Dialog 객체에서 메서드를 호출하는 대신에 사용합니다.

DialogFragment를 사용하여 대화상자를 올바르게 관리하면 올바르게 실행됨 사용자가 뒤로 버튼을 탭하거나 화면을 회전할 때와 같은 수명 주기 이벤트를 처리합니다. 화면 또한 DialogFragment 클래스를 사용하면 대화상자의 UI를 더 큰 UI에 삽입 가능한 구성요소로 정의합니다. 전통적인 Fragment: 다음과 같이 화면의 크기에 따라 대화상자 UI가 다르게 표시되도록 할 수 있습니다. 사용할 수 있습니다.

이 문서의 다음 섹션에서는 DialogFragmentAlertDialog 조합 객체를 지정합니다. 날짜 또는 시간 선택 도구를 만들려면 다음을 참고하세요. 선택 도구를 앱을 엽니다.

대화상자 프래그먼트 만들기

사용자 지정 대화 상자를 비롯하여 다양한 대화상자 디자인을 만들 수 있습니다. 다음에 설명된 레이아웃과 머티리얼 디자인 대화상자: 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")
    }
}

자바

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. 메시지 1개와 2개의 대화상자가 있는 대화상자 실행할 수 있습니다

다음 섹션에서는 AlertDialog.Builder API를 사용하여 대화상자를 만듭니다

대화의 복잡한 정도에 따라 다양한 DialogFragment의 다른 콜백 메서드도 포함되어야 합니다. 기본적인 프래그먼트 수명 주기 메서드를 사용합니다.

알림 대화상자 빌드

AlertDialog 클래스를 사용하면 다양한 대화상자를 빌드할 수 있습니다. 이것만 필요한 유일한 대화상자 클래스인 경우가 많습니다. 다음에 나와 있습니다. 알림 대화상자에는 세 가지 영역이 있습니다.

  • 제목: 선택사항이며 콘텐츠 영역이 자세한 메시지, 목록 또는 맞춤 레이아웃이 사용됩니다. 필요한 경우 간단한 메시지나 질문을 언급할 경우 제목이 필요하지 않습니다.
  • 콘텐츠 영역: 메시지, 목록 또는 기타 맞춤 항목을 있습니다.
  • 작업 버튼: 작업 버튼에는 작업 버튼을 최대 3개까지 대화상자

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

자바

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

이전 코드 스니펫은 다음 대화상자를 생성합니다.

제목, 콘텐츠 영역, 작업 버튼 2개가 있는 대화상자를 보여주는 이미지입니다.
그림 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()

자바

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

set...Button() 메서드에는 버튼에 의해 문자열 리소스 및 a DialogInterface.OnClickListener - 사용자가 버튼을 탭할 때 실행할 작업을 정의합니다.

추가할 수 있는 작업 버튼은 세 가지입니다.

  • 긍정적: 작업을 수락하고 계속하는 데 사용합니다( "확인" 합니다.
  • 음수: 작업을 취소하는 데 사용합니다.
  • 중립: 사용자가 취소할 필요는 없습니다. 인코더-디코더는 긍정적 버튼과 부정적 버튼이 있습니다. 예를 들어 "알려 줘"라고 요청할 수 있습니다 확인할 수 있습니다.

AlertDialog에는 각 버튼 유형을 하나씩만 추가할 수 있습니다. 대상 예를 들어 '긍정적'이라는 단어는 2개 이상 사용할 수 없습니다. 버튼을 클릭합니다.

이전 코드 스니펫은 다음과 같은 알림 대화상자를 제공합니다.

제목, 메시지, 작업 버튼 2개가 있는 알림 대화상자를 보여주는 이미지입니다.
그림 4. 제목이 있는 알림 대화상자 두 개의 작업 버튼이 있습니다.

목록 추가

AlertDialog와 함께 사용할 수 있는 목록에는 세 가지 종류가 있습니다. API:

  • 기존의 단일 선택 목록입니다.
  • 지속적인 단일 선택 목록 (라디오 버튼).
  • 지속적인 다중 선택 목록 (체크박스).

그림 5와 같은 단일 선택 목록을 만들려면 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()

자바

@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 콘텐츠가 비동기식으로 로드됩니다. 이에 대해서는 레이아웃 빌드 어댑터 로더.

<ph type="x-smartling-placeholder">

지속적인 다중 선택 또는 단일 선택 목록 추가

다중 선택 항목 (체크박스) 또는 단일 선택 항목의 목록 추가하기 (라디오 버튼) setMultiChoiceItems() 또는 setSingleChoiceItems() 메서드를 사용하세요.

예를 들어 다음과 같은 객관식 목록을 만드는 방법은 다음과 같습니다. Cloud Functions는 선택한 항목을 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()

자바

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

자바

        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>
<ph type="x-smartling-placeholder">

DialogFragment에서 레이아웃을 확장하려면 다음을 가져옵니다. LayoutInflater 다음 코드로 교체합니다. <ph type="x-smartling-placeholder">getLayoutInflater()</ph> 및 호출 inflate()입니다. 첫 번째 매개변수는 레이아웃 리소스 ID이고 두 번째 매개변수는 레이아웃의 상위 뷰입니다. 그런 다음 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")
}

자바

@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 Dialog API를 사용하는 대신 대화상자를 표시합니다. 활동을 만들고 테마를 다음으로 설정 Theme.Holo.Dialog<activity> 매니페스트 요소의 하위 요소로서

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

이제 활동이 대화상자를 전체 화면이 아니라 대화상자 창으로 표시합니다.

이벤트를 대화상자의 호스트에 다시 전달

사용자가 대화상자의 작업 버튼 중 하나를 탭하거나 항목을 선택할 때 DialogFragment이(가) 목록에 있는 경우 필요한 작업을 수행하지만 활동을 액티비티나 프래그먼트를 표시합니다. 이를 위해 메서드와 함께 인터페이스를 정의합니다. 를 사용합니다. 그런 다음 이 인터페이스를 호스트 이 구성요소를 호출할 수 있습니다.

예를 들어 다음은 인터페이스를 정의하는 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"))
        }
    }
}

자바

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.
    }
}

자바

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() 콜백 메서드를 호출할 수 있습니다. 대화상자 프래그먼트는 인터페이스 콜백 메서드를 사용하여 클릭 이벤트를 활동에 전달합니다.

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

자바

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(), 전달 <ph type="x-smartling-placeholder">FragmentManager</ph> 대화상자 프래그먼트의 태그 이름이 있어야 합니다.

다음을 호출하여 FragmentManager를 가져올 수 있습니다. getSupportFragmentManager() - <ph type="x-smartling-placeholder">FragmentActivity</ph> 또는 getParentFragmentManager() (Fragment에서 가져옴) 다음 예를 참고하세요.

Kotlin

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

자바

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

두 번째 인수 "game"는 시스템은 필요한 경우 프래그먼트 상태를 저장하고 복원하는 데 사용합니다. 또한 태그는 를 호출하여 프래그먼트에 핸들을 가져올 수 있습니다. findFragmentByTag()

대화상자를 전체 화면으로 표시하거나 삽입된 프래그먼트로 표시

일부 UI 디자인이 대화상자로 나타나도록 전체 화면 또는 다른 상황에서 삽입된 프래그먼트로 표현됩니다. 다음 작업도 할 수 있습니다. 기기의 화면 크기에 따라 다르게 표시되도록 할 수 있습니다. 이 DialogFragment 클래스를 사용하면 이 작업을 실행할 수 있습니다. 삽입 가능한 Fragment로 동작할 수 있기 때문입니다.

하지만 AlertDialog.Builder 또는 Dialog 객체를 사용하여 이 경우 대화상자를 빌드합니다. 이 DialogFragment를 삽입할 수 있게 하려면 대화상자의 UI를 다음 위치에 레이아웃을 로드한 후 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
    }
}

자바

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

다음 예는 프래그먼트를 대화상자로 표시할지 아니면 프래그먼트를 표시할지를 결정합니다. 화면 크기에 따라 전체 화면 UI를 구현합니다.

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

자바

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 부울은 현재 기기는 앱의 대형 레이아웃 디자인을 사용해야 하므로 프래그먼트를 전체 화면이 아니라 대화상자로 만듭니다. 이러한 종류의 광고 단위를 설정하는 가장 좋은 방법은 부울은 bool 리소스 값대체 리소스 값을 제공해야 합니다. 예를 들어 다음은 여러 가지 화면 크기에 관한 두 가지 버전의 부울 리소스입니다.

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

자바

boolean isLargeLayout;

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

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

활동을 대형 화면에 대화상자로 표시

작은 화면에서 대화상자를 전체 화면 UI로 표시하는 대신 큰 화면의 대화상자로 Activity를 표시하여 동일한 결과 사용할 수 있습니다. 선택하는 접근 방식은 앱 디자인에 따라 다르지만 대화상자 활동은 앱이 작은 크기의 화면에 적합하도록 설계되었을 때 태블릿에서의 경험을 개선하려는 경우 단기 활동을 대화상자로 만드는 것이 좋습니다

활동을 대형 화면에만 대화상자로 표시하려면 Theme.Holo.DialogWhenLarge <activity> 매니페스트 요소에 테마를 추가합니다.

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

활동을 테마로 스타일을 지정하는 방법에 관한 자세한 내용은 다음을 참고하세요. 스타일 및 테마:

대화상자 닫기

사용자가 AlertDialog.Builder이면 시스템에서 대화상자를 닫습니다.

또한 시스템은 사용자가 대화상자에서 항목을 탭할 때 대화상자를 닫습니다. (목록에서 라디오 버튼이나 체크박스를 사용하는 경우는 제외) 그렇지 않은 경우 를 호출하여 대화상자를 수동으로 닫을 수 있습니다. dismiss() DialogFragment

대화상자가 사라질 때 특정 작업을 수행해야 하는 경우 구현하고 onDismiss() DialogFragment에 있습니다.

또한 대화상자를 취소할 수도 있습니다. 이번 특별 이벤트로 사용자가 작업을 완료하지 않고 대화상자를 떠나고 있음을 나타냅니다. 이 사용자가 뒤로 버튼을 탭하거나 대화상자 바깥의 화면을 탭하면 발생합니다. 또는 명시적으로 cancel() Dialog에서(예: 'Cancel'에 대한 응답) 버튼을 대화상자

앞의 예에서와 같이 취소 이벤트에 다음과 같이 응답할 수 있습니다. 구현 onCancel() DialogFragment 수업에서 확인할 수 있습니다.

<ph type="x-smartling-placeholder">