Skip to content

Android.app.AlertDialog

display a pop-up window with buttons.

Simple example

AlertDialog ad = new AlertDialog.Builder(getActivity()).create();
ad.setCancelable(false);
ad.setMessage("ALERT MESSAGE");
ad.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});
ad.show();

AlertDialog 메시지 창 띄우기

// 메세지를 띄우고 [확인] 버튼만 적용할 경우
AlertDialog.Builder alert = new AlertDialog.Builder(MyActivity.this);
alert.setPositiveButton("확인", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss(); // 닫기
    }
});
alert.setMessage("테스트 메세지");
alert.show();

// 메세지를 띄우고 [확인], [취소] 버튼으로 적용할 경우
AlertDialog.Builder alert_confirm = new AlertDialog.Builder(MyActivity.this);
alert_confirm.setMessage("프로그램을 종료 하시겠습니까?").setCancelable(false)
        .setPositiveButton("확인", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 'YES'
            }
        }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 'No'
                return;
            }
        });
AlertDialog alert = alert_confirm.create();
alert.show();

위와 같이 작업했을 경우, 차후 메모리릭을 방지하기 위해 아래와 같은 코드를 추가해야 한다.

alert.dismiss();

텍스트 입력이 가능한 AlertDialog

AlertDialog.Builder alert = new AlertDialog.Builder(this);

alert.setTitle("Title");
alert.setMessage("Message");

// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        String value = input.getText().toString();
        value.toString();
        // Do something with value!
    }
});

alert.setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // Canceled.
            }
        });

alert.show(); 

See also

Favorite site

References


  1. Android_custom_dialog.pdf 

  2. Android_activity_theme_popup_dialog.pdf