내가 하는일/JAVA

안드로이드 다이얼로그 구현

Tenin 2011. 9. 20. 15:07

다중선택을 위한 다이얼로그 창을 띄운다. 리스트에는 제목과 radio button

이 있다. AlertDialog.Builder 클래스로 구현하며 리스트중 특정행을 클릭했을 때

이벤트는 setSingleChoiceItems 에 등록한다. Ok 버튼클릭 이벤트는

setPositiveButton , Cancel 버튼클릭 이벤트는 setNegativeButton 에 등록하고

기능을 구현하면 된다.


 

01 private void DialogSelectOption() {
02 final String items[] = { "item1", "item2", "item3" };
03 AlertDialog.Builder ab = new AlertDialog.Builder(DialogSample.this);
04 ab.setTitle("Title");
05 ab.setSingleChoiceItems(items, 0,
06 new DialogInterface.OnClickListener() {
07 public void onClick(DialogInterface dialog, int whichButton) {
08 // 각 리스트를 선택했을때
09 }
10 }).setPositiveButton("Ok",
11 new DialogInterface.OnClickListener() {
12 public void onClick(DialogInterface dialog, int whichButton) {
13 // OK 버튼 클릭시 , 여기서 선택한 값을 메인 Activity 로 넘기면 된다.
14 }
15 }).setNegativeButton("Cancel",
16 new DialogInterface.OnClickListener() {
17 public void onClick(DialogInterface dialog, int whichButton) {
18 // Cancel 버튼 클릭시
19 }
20 });
21 ab.show();
22 }

(2) html 로 구현한 text 넣기

다이얼로그 창을 띄울 때 공지나 경고성 창이라면 내용이 들어갈것이다. 이 내용을

HTML 태그를 적용해 넣을 수가 있다. 색깔은 제대로 바뀌는 것 같은데 <strong>, <b>

등 글자에 대한 bold 처리가 한거나 안한거나 똑같이 보여서 제대로 표현되는지는

좀더 테스트 해봐야할것같다.

01 private void DialogHtmlView(){
02 AlertDialog.Builder ab=new AlertDialog.Builder(DialogSample.this);
03 ab.setMessage(Html.fromHtml("<STRONG><FONT color=#ff0000> " +
04 "Html 표현여부 " +"</FONT></STRONG><BR>
05
06
07 HTML 이 제대로 표현되는지 본다."));
08 ab.setPositiveButton("ok", null);
09 ab.show();
10 }

(3) 프로그레시브(Progress) 다이얼로그 구현

안드로이드에서 프로그레시브바를 구현할수 있다. 이것을 구현하기 위한 클래스는

ProgressDialog 를 사용해야 한다. 다이얼로그 창의 중지는 ProgressDialog

dismiss 를 쓰면된다.

1 private void DialogProgress(){
2 ProgressDialog dialog = ProgressDialog.show(DialogSample.this, "",
3 "잠시만 기다려 주세요 ...", true);
4 // 창을 내린다.
5 // dialog.dismiss();
6 }

aaa

(4) Radio 버튼을 포함한 다중선택 다이얼로그 창

1번 예제와 비슷하게 Radio 버튼이 추가되어있는 다중선택 다이얼로그 창이다.

차이가 있다면 창 타이틀에 setIcon 을 써서 아이콘을 집어넣은것과

선택한 행 번호를 알아와 Toast 로 화면에 문자열을 표시해주는 내용이다.

창을 닫고 싶다면 onclick 함수에 넘어온 DialogInterface 객체로 cancel 함수를

호출해 닫으면 된다.

01 private void DialogRadio(){
02 final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"};
03 AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
04 alt_bld.setIcon(R.drawable.icon);
05 alt_bld.setTitle("Select a Phone Model");
06 alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() {
07 public void onClick(DialogInterface dialog, int item) {
08 Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item], Toast.LENGTH_SHORT).show();
09 // dialog.cancel();
10 }
11 });
12 AlertDialog alert = alt_bld.create();
13 alert.show();
14 }

(5) 선택에 따른 로직구현을 위한 다이얼로그 창 구현

예를 들어 Yes/No 중 하나를 선택함으로서 특정 기능을 구현해주고자 할 때

쓰일만한 예제이다. 샘플에서는 Yes/No 일때를 구분하여 코드를 구현할수

있도록 나누어져 있다. 우리가 흔히 보는 대표적인 다이얼로그 창일것이다.

01 private void DialogSimple(){
02 AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
03 alt_bld.setMessage("Do you want to close this window ?").setCancelable(
04 false).setPositiveButton("Yes",
05 new DialogInterface.OnClickListener() {
06 public void onClick(DialogInterface dialog, int id) {
07 // Action for 'Yes' Button
08 }
09 }).setNegativeButton("No",
10 new DialogInterface.OnClickListener() {
11 public void onClick(DialogInterface dialog, int id) {
12 // Action for 'NO' Button
13 dialog.cancel();
14 }
15 });
16 AlertDialog alert = alt_bld.create();
17 // Title for AlertDialog
18 alert.setTitle("Title");
19 // Icon for AlertDialog
20 alert.setIcon(R.drawable.icon);
21 alert.show();
22 }

aaaa

(6) Time Picker 시간선택 컨트롤을 다이얼로그에 구현

Time Picker 컨트롤을 다이얼로그 창에 구현한 예제이다. 그리고 다이얼로그에

구현되어있는 Time Picker 에서 선택한 값을 부모 화면에서 받아 그 값을 Toast

로 보여준다

01 private void DialogTimePicker(){
02 TimePickerDialog.OnTimeSetListener mTimeSetListener =
03 new TimePickerDialog.OnTimeSetListener() {
04 public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
05 Toast.makeText(DialogSample.this,
06 "Time is=" + hourOfDay + ":" + minute, Toast.LENGTH_SHORT)
07 .show();
08 }
09 };
10 TimePickerDialog alert = new TimePickerDialog(this,
11 mTimeSetListener, 0, 0, false);
12 alert.show();
13 }

(7) Date Picker 날짜선택 컨트롤을 다이얼로그에 구현

Date Picker 컨트롤을 다이얼로그 창에 구현한 예제이다. 그리고 다이얼로그에

구현되어있는 Date Picker 에서 선택한 값을 부모 화면에서 받아 그 값을 Toast

로 보여준다. 창을 띄우기 전에 현재 날짜정보를 넘겨주고 Date Picker 에서는

그것을 받아 표시해 준다.

01 private void DialogDatePicker(){
02 Calendar c = Calendar.getInstance();
03 int cyear = c.get(Calendar.YEAR);
04 int cmonth = c.get(Calendar.MONTH);
05 int cday = c.get(Calendar.DAY_OF_MONTH);
06
07 DatePickerDialog.OnDateSetListener mDateSetListener =
08 new DatePickerDialog.OnDateSetListener() {
09 // onDateSet method
10 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
11 String date_selected = String.valueOf(monthOfYear+1)+
12 " /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);
13 Toast.makeText(DialogSample.this,
14 "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
15 }
16 };
17 DatePickerDialog alert = new DatePickerDialog(this, mDateSetListener,
18 cyear, cmonth, cday);
19 alert.show();
20 }

aaaa

(8) 전체 소스

001 import java.util.ArrayList;
002 import java.util.Calendar;
003 import java.util.HashMap;
004 import java.util.List;
005 import java.util.Map;
006
007 import android.app.AlertDialog;
008 import android.app.DatePickerDialog;
009 import android.app.ListActivity;
010 import android.app.ProgressDialog;
011 import android.app.TimePickerDialog;
012 import android.content.DialogInterface;
013 import android.os.Bundle;
014 import android.text.Html;
015 import android.util.Log;
016 import android.view.View;
017 import android.widget.DatePicker;
018 import android.widget.ListView;
019 import android.widget.SimpleAdapter;
020 import android.widget.TimePicker;
021 import android.widget.Toast;
022
023 import com.sample.R;
024
025 public class DialogSample extends ListActivity {
026
027 private String[] mMenuText;
028 private String[] mMenuSummary;
029
030 private String keyName = "name";
031 private String keyDesc = "desc";
032 private String TAG;
033
034 /** Called when the activity is first created. */
035 @Override
036 public void onCreate(Bundle savedInstanceState) {
037 super.onCreate(savedInstanceState);
038 TAG = getClass().getName();
039
040 int length = 7;
041 mMenuText = new String[length];
042 mMenuSummary = new String[length];
043
044 mMenuText[0] = "다중선택 새창";
045 mMenuSummary[0] = "다중선택을 할수 있는 Alert 예제구현이다.";
046 mMenuText[1] = "HTML 적용 새창";
047 mMenuSummary[1] = "Text 에 HTML 을 적용하는 Alert 예제구현이다.";
048 mMenuText[2] = "프로그레시브바 새창";
049 mMenuSummary[2] = "진행중을 나타내는 프로그레시브바 Alert 예제구현다.";
050 mMenuText[3] = "Radio 버튼 새창";
051 mMenuSummary[3] = "Radio 버튼이 들어간 새창 이며 선택하면 창이 닫힌다. ";
052 mMenuText[4] = "Simple Dialog";
053 mMenuSummary[4] = "선택에 따른 로직구현을 위한 다이얼로그 창 구현";
054 mMenuText[5] = "Time Picker";
055 mMenuSummary[5] = "Time Picker 시간선택 컨트롤을 다이얼로그에 구현";
056 mMenuText[6] = "Date Picker";
057 mMenuSummary[6] = "Date Picker 날짜선택 컨트롤을 다이얼로그에 구현";
058
059 setListAdapter(new SimpleAdapter(this, getListValues(),
060 android.R.layout.simple_list_item_2, new String[] { keyName,
061 keyDesc }, new int[] { android.R.id.text1,
062 android.R.id.text2 }));
063 }
064
065 private List<MAP><STRING, String="">> getListValues() {
066 List<MAP><STRING, String="">> values = new ArrayList<MAP><STRING, String="">>();
067 int length = mMenuText.length;
068 for (int i = 0; i < length; i++) {
069 Map<STRING, String=""> v = new HashMap<STRING, String="">();
070 v.put(keyName, mMenuText[i]);
071 v.put(keyDesc, mMenuSummary[i]);
072 values.add(v);
073 }
074 return values;
075 }
076
077 @Override
078 protected void onListItemClick(ListView l, View v, int position, long id) {
079 super.onListItemClick(l, v, position, id);
080 Log.d(TAG, "id : " + id + ", position : " + position);
081 switch (position) {
082 case 0:
083 // 다중선택 옵션창
084 this.DialogSelectOption();
085 break;
086 case 1:
087 // HTML 구현
088 this.DialogHtmlView();
089 break;
090 case 2:
091 // 프로그레시브바 구현
092 this.DialogProgress();
093 break;
094 case 3:
095 // Radio 버튼이 추가된 다중선택 창
096 this.DialogRadio();
097 break;
098 case 4:
099 // 가장 일반적인 Yes/NO기능구현 Dialog
100 this.DialogSimple();
101 break;
102 case 5:
103 this.DialogTimePicker();
104 break;
105 case 6:
106 // 날짜 선택 Dialog 구현
107 this.DialogDatePicker();
108 break;
109 default:
110 break;
111 }
112 }
113
114 private void DialogSelectOption() {
115 final String items[] = { "item1", "item2", "item3" };
116 AlertDialog.Builder ab = new AlertDialog.Builder(DialogSample.this);
117 ab.setTitle("Title");
118 ab.setSingleChoiceItems(items, 0,
119 new DialogInterface.OnClickListener() {
120 public void onClick(DialogInterface dialog, int whichButton) {
121 // 각 리스트를 선택했을때
122 }
123 }).setPositiveButton("Ok",
124 new DialogInterface.OnClickListener() {
125 public void onClick(DialogInterface dialog, int whichButton) {
126 // OK 버튼 클릭시 , 여기서 선택한 값을 메인 Activity 로 넘기면 된다.
127 }
128 }).setNegativeButton("Cancel",
129 new DialogInterface.OnClickListener() {
130 public void onClick(DialogInterface dialog, int whichButton) {
131 // Cancel 버튼 클릭시
132 }
133 });
134 ab.show();
135 }
136
137 private void DialogHtmlView(){
138 AlertDialog.Builder ab=new AlertDialog.Builder(DialogSample.this);
139 ab.setMessage(Html.fromHtml("<STRONG><FONT color=#ff0000> " +
140 "Html 표현여부 " +"</FONT></STRONG><BR>
141
142
143
144 HTML 이 제대로 표현되는지 본다."));
145 ab.setPositiveButton("ok", null);
146 ab.show();
147 }
148
149 private void DialogProgress(){
150 ProgressDialog dialog = ProgressDialog.show(DialogSample.this, "",
151 "잠시만 기다려 주세요 ...", true);
152
153 // 창을 내린다.
154 // dialog.dismiss();
155 }
156
157 private void DialogRadio(){
158 final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"};
159 AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
160 alt_bld.setIcon(R.drawable.icon);
161 alt_bld.setTitle("Select a Phone Model");
162 alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() {
163 public void onClick(DialogInterface dialog, int item) {
164 Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item], Toast.LENGTH_SHORT).show();
165 dialog.cancel();
166 }
167 });
168 AlertDialog alert = alt_bld.create();
169 alert.show();
170 }
171
172 private void DialogSimple(){
173 AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
174 alt_bld.setMessage("Do you want to close this window ?").setCancelable(
175 false).setPositiveButton("Yes",
176 new DialogInterface.OnClickListener() {
177 public void onClick(DialogInterface dialog, int id) {
178 // Action for 'Yes' Button
179 }
180 }).setNegativeButton("No",
181 new DialogInterface.OnClickListener() {
182 public void onClick(DialogInterface dialog, int id) {
183 // Action for 'NO' Button
184 dialog.cancel();
185 }
186 });
187 AlertDialog alert = alt_bld.create();
188 // Title for AlertDialog
189 alert.setTitle("Title");
190 // Icon for AlertDialog
191 alert.setIcon(R.drawable.icon);
192 alert.show();
193 }
194
195 private void DialogTimePicker(){
196 TimePickerDialog.OnTimeSetListener mTimeSetListener =
197 new TimePickerDialog.OnTimeSetListener() {
198 public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
199 Toast.makeText(DialogSample.this,
200 "Time is=" + hourOfDay + ":" + minute, Toast.LENGTH_SHORT)
201 .show();
202 }
203 };
204 TimePickerDialog alert = new TimePickerDialog(this, mTimeSetListener, 0, 0, false);
205 alert.show();
206 }
207
208 private void DialogDatePicker(){
209 Calendar c = Calendar.getInstance();
210 int cyear = c.get(Calendar.YEAR);
211 int cmonth = c.get(Calendar.MONTH);
212 int cday = c.get(Calendar.DAY_OF_MONTH);
213
214 DatePickerDialog.OnDateSetListener mDateSetListener =
215 new DatePickerDialog.OnDateSetListener() {
216 // onDateSet method
217 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
218 String date_selected = String.valueOf(monthOfYear+1)+
219 " /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);
220 Toast.makeText(DialogSample.this,
221 "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
222 }
223 };
224 DatePickerDialog alert = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
225 alert.show();
226 }
227
228 }