2018. 1. 29. 17:24ㆍ안드로이드
#7 안드로이드 스튜디오로 안드로이드 앱 만들기 - 레이아웃(Layout)을 활용한 다양한 뷰(View) 배치 : LinearLayout편
#8 안드로이드 스튜디오로 안드로이드 앱 만들기 - 레이아웃(Layout)을 활용한 다양한 뷰(View) 배치 : RelativeLayout편
#9 안드로이드 스튜디오로 안드로이드 앱 만들기 - 레이아웃(Layout)을 활용한 다양한 뷰(View) 배치 : 탭 화면 구현 - TabHost
#10 안드로이드 스튜디오로 안드로이드 앱 만들기 - 레이아웃(Layout)을 활용한 다양한 뷰(View) 배치 : ConstraintLayout
#11 안드로이드 스튜디오로 안드로이드 앱 만들기 - 다양한 사용자 알림 효과 : 진동과 소리
사용자가 스마트폰에서 앱을 이용하고 있을 때 다양한 상황을 알리기 위해서 다이얼로그(Dialog)를 이용한다. 흔히 애플리케이션에서 다이얼로그는 크게 모달(Modal)과 모달리스(Modeless)로 구분 할 수 있다.
모달은 다이얼로그를 닫기 전까지 원래의 창을 사용 할 수 없다. 반면에 모달리스는 다이얼로그가 화면에 떠 있어도 사용자가 원래 화면을 사용할 수 있다.
안드로이드 앱에서 다이얼로그의 종류는 토스트(Toast), 알림창(AlertDialog), 목록(AlertDialog), 프로그레스 다이얼로그(ProgressDialog), 날짜 선택(DatePickerDialog), 시간 선택(TimePickerDialog), 커스텀 다이얼로그(AlertDialog)가 있다.
그럼 위와 같이 간단한 예제를 만들어보자.
Step 1_ 액티비티 생성
"Lab5_2Activity" 이름으로 새로운 액티비티를 만든다. 액티비티를 만들 때 'Launcher Activity' 체크박스를 체크한뒤에 만들면 테스트할 때 편하다.
Step 2_ 커스텀 다이얼로그 레이아웃 XML 작성
커스텀 다이얼로그 화면을 위한 새로운 XML 파일을 "dialog_layout.xml" 이름으로 생성하자. 새 레이아웃 XML 파일은 res/layout 폴더를 마우스 오른쪽으로 선택하고 [New - Layout Resource file] 메뉴를 선택하여 생성한다.
Step 3_ dialog_layout.xml 작성
스마트폰을 연결할 때 USB 디버깅 허용을 묻는 다이얼로그 화면을 그대로 만들어 보기 위해 dialog_layout.xml 파일을 작성하자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="USB 디버깅을 허용하시겠습니까 ?" android:textStyle="bold" android:textSize="15dp" android:layout_marginLeft="32dp" android:layout_marginTop="32dp"/> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="컴퓨터 RSA키 지문 : " android:layout_below="@id/text1" android:layout_alignLeft="@id/text1"/> <TextView android:id="@+id/text3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="17:AA:AA:aA:AA:AA:AA:SS:DD" android:layout_below="@id/text2" android:layout_alignLeft="@id/text2"/> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="이 컴퓨터에서 항상 허용" android:layout_below="@id/text3" android:layout_alignLeft="@id/text3"/> </RelativeLayout> |
Step 4_ activity_lab5_2.xml 작성
테스트를 위해 각 다이얼로그를 띄우는 버튼으로 구성된 레이아웃 XML을 작성하자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/btn_alert" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="alert dialog"/> <Button android:id="@+id/btn_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="list dialog"/> <Button android:id="@+id/btn_progress" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="progress dialog"/> <Button android:id="@+id/btn_date" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="date dialog"/> <Button android:id="@+id/btn_time" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="time dialog"/> <Button android:id="@+id/btn_custom" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="custom dialog"/> </LinearLayout> | cs |
Step 5_ arrays.xml 파일 생성
목록 다이얼로그를 구성하기 위한 문자열 여러 개를 리소르로 등록해서 사용해보자. values 폴더 하위에 arrays.xml 파일을 만든다. values 폴더를 마우스 오른쪽으로 선택하고 [New - Values resource file] 메뉴를 선택하면 된다.
Step 6_ arrays.xml 파일 작성
목록의 문자열을 arrays.xml에 작성하자.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="dialog_array"> <item>기본 알람 소리</item> <item>Argon</item> <item>Awaken</item> <item>Bounce</item> <item>Carbon</item> </string-array> </resources> | cs |
Step 7_ Lab5_2Activity.java 작성
버튼 이벤트 프로그램을 통해 각 다이얼로그를 띄우는 자바 코드를 작성하자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | package com.example.part2_5; import android.app.DatePickerDialog; import android.app.ProgressDialog; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TimePicker; import android.widget.Toast; import java.util.Calendar; public class Lab5_2Activity extends AppCompatActivity implements View.OnClickListener{ Button alertBtn; Button listBtn; Button progressBtn; Button dateBtn; Button timeBtn; Button customDialogBtn; //이벤트 처리를 위해 dialog 객체를 멤버 변수로 선언 AlertDialog customDialog; AlertDialog listDialog; AlertDialog alertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lab5_2); //view 객체 획등 alertBtn=(Button)findViewById(R.id.btn_alert); listBtn=(Button)findViewById(R.id.btn_list); progressBtn=(Button)findViewById(R.id.btn_progress); dateBtn=(Button)findViewById(R.id.btn_date); timeBtn=(Button)findViewById(R.id.btn_time); customDialogBtn=(Button)findViewById(R.id.btn_custom); //버튼 이벤트 등록 alertBtn.setOnClickListener(this); listBtn.setOnClickListener(this); progressBtn.setOnClickListener(this); dateBtn.setOnClickListener(this); timeBtn.setOnClickListener(this); customDialogBtn.setOnClickListener(this); } //매개변수의 문자열을 Toast로 띄우는 개발자 함수 private void showToast(String message){ Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT); toast.show(); } //dialog Button 이벤트 처리 DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(dialog==customDialog && which == DialogInterface.BUTTON_POSITIVE){ showToast("custom dialog 확인 click..."); }else if(dialog==listDialog){ //목록 dialog의 항목이 선택 되었을때 항목 문자열 획득 String[] datas=getResources().getStringArray(R.array.dialog_array); showToast(datas[which]+" 선택 했습니다."); }else if(dialog==alertDialog && which==DialogInterface.BUTTON_POSITIVE){ showToast("alert dialog OK click..."); } } }; @Override public void onClick(View v) { if(v==alertBtn){ AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle("알림"); builder.setMessage("정말 종료 할까요 ?"); builder.setPositiveButton("OK", dialogListener); builder.setNegativeButton("NO", null); alertDialog=builder.create(); alertDialog.show(); }else if(v==listBtn){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("알람 벨소리"); builder.setSingleChoiceItems(R.array.dialog_array, 0, dialogListener); builder.setPositiveButton("확인", null); builder.setNegativeButton("취소", null); listDialog=builder.create(); listDialog.show(); }else if(v==progressBtn){ ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setIcon(android.R.drawable.ic_dialog_alert); progressDialog.setTitle("Wait..."); progressDialog.setMessage("서버 연동중입니다. 잠시만 기다리세요.."); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setIndeterminate(true); progressDialog.show(); }else if(v==dateBtn){ //현재 날짜로 dialog를 띄우기 위해 날짜를 구함 Calendar c = Calendar.getInstance(); int y = c.get(Calendar.YEAR); int m = c.get(Calendar.MONTH); final int d = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int y, int m, int d) { showToast(y+"_"+(m+1)+"_"+d); } }, y, m, d); datePickerDialog.show(); }else if(v==timeBtn){ //현재 시간으로 Dialog르 띄우기 위해 시간을 구함 Calendar c= Calendar.getInstance(); int h = c.get(Calendar.HOUR_OF_DAY); int m = c.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int h, int m) { showToast(h+" : "+m); } }, h, m ,false); timePickerDialog.show(); }else if(v==customDialogBtn){ AlertDialog.Builder builder = new AlertDialog.Builder(this); //custom dialog를 위한 layout xml 초기화 LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dialog_layout, null); builder.setView(view); builder.setPositiveButton("확인", dialogListener); builder.setNegativeButton("취소", null); customDialog=builder.create(); customDialog.show(); } } } | cs |
Step 8_ Lab5_2Activity.java 실행
액티비티를 만들 때 'Launcher Activity' 체크박스를 체크하였으면 Lab5_2Activity.java 파일에 마우스 오른쪽을 누르고, [Run 'Lab5_2Activity.java'] 메뉴를 눌러 실행하면 된다.