알림 대화상자(Alert Dialog)를 본격적으로 다루기 전에, 먼저 알림 대화상자가 무엇인지 이해할 필요가 있습니다. 알림 대화상자는 팝업 창과 유사한 UI 요소로, 사용자가 "확인" 또는 "취소" 버튼을 클릭하여 원하는 동작을 선택할 수 있도록 해줍니다.
알림 대화상자의 주요 메서드
setView(View view) − 알림 대화상자에 사용자 지정 뷰(Custom View)를 설정합니다.
setTitle(CharSequence title) − 알림 대화상자의 제목을 설정합니다.
setMessage(CharSequence message) − 알림 상자에 표시될 내용(메시지)을 설정합니다.
setIcon(int resId) − 알림 상자에 아이콘을 설정합니다.
setButton(int whichButton, CharSequence text, Message msg) − 알림 대화상자에 버튼을 설정합니다. 자세한 내용은 아래 예제를 참고하세요.
getListView() − 알림 대화상자 내부에서 사용되는 리스트뷰(ListView)를 가져옵니다.
이번 예제를 통해 안드로이드에서 알림 대화상자를 구현하는 방법을 단계별로 살펴보겠습니다.
1단계 − Android Studio에서 새 프로젝트를 생성합니다. File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.
2단계 − res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:app = "https://schemas.android.com/apk/res-auto" xmlns:tools = "https://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Click" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout>
3단계 − src/MainActivity.java 파일에 다음 코드를 추가합니다.
package com.example.andy.myapplication;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
alertDialog();
break;
}
}
private void alertDialog() {
AlertDialog.Builder dialog=new AlertDialog.Builder(this);
dialog.setMessage("Please Select any option");
dialog.setTitle("Dialog Box");
dialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
}
});
dialog.setNegativeButton("cancel",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"cancel is clicked",Toast.LENGTH_LONG).show();
}
});
AlertDialog alertDialog=dialog.create();
alertDialog.show();
}
}위 코드에서는 화면에 버튼 하나를 배치했습니다. 사용자가 이 버튼을 클릭하면 알림 대화상자가 나타나며, 사용자는 필요에 따라 "YES" 또는 "cancel" 버튼을 선택할 수 있습니다.
이제 애플리케이션을 직접 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run 아이콘을 클릭합니다. 그다음 옵션 목록에서 자신의 모바일 기기를 선택하고, 기기 화면에 기본 화면이 정상적으로 표시되는지 확인합니다.

이제 화면의 버튼을 클릭하면 아래 이미지와 같은 알림 대화상자가 표시됩니다.

여기서 YES 또는 cancel 버튼을 선택하면 각각의 클릭 결과가 아래 이미지와 같이 토스트(Toast) 메시지로 출력됩니다.

