본문 바로가기

Android/AlertDialog example

Android AlertDialog example

Android 에서 AlertDialog을 생성하고 각 버튼이 눌릴 때 이벤트를 처리하는 예

TestActivity.java

package com.example.androidapp; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; public class TestActivity extends Activity implements DialogInterface.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AlertDialog alertDlg = null; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("안내"); builder.setMessage("정말로 종료하시겠습니까"); builder.setIcon(R.drawable.ic_launcher); builder.setPositiveButton("예", this); builder.setNeutralButton("취소", this); builder.setNegativeButton("아니오", this); alertDlg = builder.create(); alertDlg.show(); } public void onClick(DialogInterface dialog, int which) { String msg = null; switch(which) { case Dialog.BUTTON_POSITIVE: msg = "YES "+which; break; case Dialog.BUTTON_NEUTRAL: msg = "CANCEL "+which; break; case Dialog.BUTTON_NEGATIVE: msg = "NO "+which; break; } Toast.makeText(this, "이용자 선택:"+msg, Toast.LENGTH_LONG).show(); } }