티스토리 뷰

study/Android

[Android] Dialog

koreaparks 2014. 1. 13. 15:41

다이얼로그를 매우 잘 정리해둔 블로그가 있어 가져왔습니다.

출처: http://mainia.tistory.com/555 (녹두장군님 블로그)

 

(1) 여러 개의 멀티선택 옵션으로 표현해 주기

 

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

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

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

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

기능을 구현하면 된다.


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

 

(2) html 로 구현한 text 넣기

 

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

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

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

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

1
2
3
4
5
6
7
8
9
10
private void DialogHtmlView(){
AlertDialog.Builder ab=new AlertDialog.Builder(DialogSample.this);
    ab.setMessage(Html.fromHtml("<strong><font color="#ff0000"> " +
        "Html 표현여부 " +"</font></strong><br><span id="callbacknestmainiatistorycom5552690" style="width:1px; height:1px; float:right"><embed allowscriptaccess="always" id="bootstrappermainiatistorycom5552690" src="http://mainia.tistory.com/plugin/CallBack_bootstrapperSrc?nil_profile=tistory&nil_type=copied_post" width="1" height="1" wmode="transparent" type="application/x-shockwave-flash" enablecontextmenu="false" flashvars="&callbackId=mainiatistorycom5552690&host=http://mainia.tistory.com&embedCodeSrc=http%3A%2F%2Fmainia.tistory.com%2Fplugin%2FCallBack_bootstrapper%3F%26src%3Dhttp%3A%2F%2Fs1.daumcdn.net%2Fcfs.tistory%2Fv%2F0%2Fblog%2Fplugins%2FCallBack%2Fcallback%26id%3D555%26callbackId%3Dmainiatistorycom5552690%26destDocId%3Dcallbacknestmainiatistorycom5552690%26host%3Dhttp%3A%2F%2Fmainia.tistory.com%26float%3Dleft" swliveconnect="true"></span>
 
 
HTML 이 제대로 표현되는지 본다."));
        ab.setPositiveButton("ok", null);
        ab.show();
}

 

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

 

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

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

dismiss 를 쓰면된다.

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

aaa

 

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

 

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

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

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

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

호출해 닫으면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void DialogRadio(){
final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"};
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setIcon(R.drawable.icon);
        alt_bld.setTitle("Select a Phone Model");
        alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item], Toast.LENGTH_SHORT).show();
                // dialog.cancel();
            }
        });
        AlertDialog alert = alt_bld.create();
        alert.show();
}

 

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

 

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private void DialogSimple(){
    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    alt_bld.setMessage("Do you want to close this window ?").setCancelable(
        false).setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // Action for 'Yes' Button
        }
        }).setNegativeButton("No",
        new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // Action for 'NO' Button
            dialog.cancel();
        }
        });
    AlertDialog alert = alt_bld.create();
    // Title for AlertDialog
    alert.setTitle("Title");
    // Icon for AlertDialog
    alert.setIcon(R.drawable.icon);
    alert.show();
}

aaaa

 

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

 

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

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

로 보여준다

1
2
3
4
5
6
7
8
9
10
11
12
13
private void DialogTimePicker(){
    TimePickerDialog.OnTimeSetListener mTimeSetListener =
    new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Toast.makeText(DialogSample.this,
            "Time is=" + hourOfDay + ":" + minute, Toast.LENGTH_SHORT)
            .show();
        }
    };
    TimePickerDialog alert = new TimePickerDialog(this,
mTimeSetListener, 0, 0, false);
    alert.show();
}

 

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

 

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

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

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

그것을 받아 표시해 준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void DialogDatePicker(){
    Calendar c = Calendar.getInstance();
    int cyear = c.get(Calendar.YEAR);
    int cmonth = c.get(Calendar.MONTH);
    int cday = c.get(Calendar.DAY_OF_MONTH);
     
    DatePickerDialog.OnDateSetListener mDateSetListener =
    new DatePickerDialog.OnDateSetListener() {
    // onDateSet method
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
         String date_selected = String.valueOf(monthOfYear+1)+
                " /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);
         Toast.makeText(DialogSample.this,
        "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
    }
     };
     DatePickerDialog alert = new DatePickerDialog(this,  mDateSetListener, 
     cyear, cmonth, cday);
     alert.show();
}

aaaa

 

(8) 전체 소스

 

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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TimePicker;
import android.widget.Toast;
 
import com.sample.R;
 
public class DialogSample extends ListActivity {
 
    private String[] mMenuText;
    private String[] mMenuSummary;
 
    private String keyName = "name";
    private String keyDesc = "desc";
    private String TAG;
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getName();
 
        int length = 7;
        mMenuText = new String[length];
        mMenuSummary = new String[length];
 
        mMenuText[0] = "다중선택 새창";
        mMenuSummary[0] = "다중선택을 할수 있는 Alert 예제구현이다.";
        mMenuText[1] = "HTML 적용 새창";
        mMenuSummary[1] = "Text 에 HTML 을 적용하는 Alert 예제구현이다.";
        mMenuText[2] = "프로그레시브바 새창";
        mMenuSummary[2] = "진행중을 나타내는 프로그레시브바 Alert 예제구현다.";
        mMenuText[3] = "Radio 버튼 새창";
        mMenuSummary[3] = "Radio 버튼이 들어간 새창 이며 선택하면 창이 닫힌다. ";
        mMenuText[4] = "Simple Dialog";
        mMenuSummary[4] = "선택에 따른 로직구현을 위한 다이얼로그 창 구현";
        mMenuText[5] = "Time Picker";
        mMenuSummary[5] = "Time Picker 시간선택 컨트롤을 다이얼로그에 구현";
        mMenuText[6] = "Date Picker";
        mMenuSummary[6] = "Date Picker 날짜선택 컨트롤을 다이얼로그에 구현";
 
        setListAdapter(new SimpleAdapter(this, getListValues(),
                android.R.layout.simple_list_item_2, new String[] { keyName,
                        keyDesc }, new int[] { android.R.id.text1,
                        android.R.id.text2 }));
    }
 
    private List<map><string, string="">> getListValues() {
        List<map><string, string="">> values = new ArrayList<map><string, string="">>();
        int length = mMenuText.length;
        for (int i = 0; i < length; i++) {
            Map<string, string=""> v = new HashMap<string, string="">();
            v.put(keyName, mMenuText[i]);
            v.put(keyDesc, mMenuSummary[i]);
            values.add(v);
        }
        return values;
    }
 
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Log.d(TAG, "id : " + id + ", position : " + position);
        switch (position) {
        case 0:
            // 다중선택 옵션창
            this.DialogSelectOption();
            break;
        case 1:
            // HTML 구현
            this.DialogHtmlView();
            break;
        case 2:
            // 프로그레시브바 구현
            this.DialogProgress();
            break;
        case 3:
            //  Radio 버튼이 추가된 다중선택 창
            this.DialogRadio();
            break;
        case 4:
            // 가장 일반적인 Yes/NO기능구현 Dialog
            this.DialogSimple();
            break;
        case 5:
            this.DialogTimePicker();
            break;
        case 6:
            // 날짜 선택 Dialog 구현
            this.DialogDatePicker();
            break;
        default:
            break;
        }
    }
 
    private void DialogSelectOption() {
        final String items[] = { "item1", "item2", "item3" };
        AlertDialog.Builder ab = new AlertDialog.Builder(DialogSample.this);
        ab.setTitle("Title");
        ab.setSingleChoiceItems(items, 0,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // 각 리스트를 선택했을때
                }
            }).setPositiveButton("Ok",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // OK 버튼 클릭시 , 여기서 선택한 값을 메인 Activity 로 넘기면 된다.
                }
            }).setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // Cancel 버튼 클릭시
                }
            });
        ab.show();
    }
     
    private void DialogHtmlView(){
        AlertDialog.Builder ab=new AlertDialog.Builder(DialogSample.this);
        ab.setMessage(Html.fromHtml("<strong><font color="#ff0000"> " +
                "Html 표현여부 " +"</font></strong><br>
 
 
 
HTML 이 제대로 표현되는지 본다."));
            ab.setPositiveButton("ok", null);
            ab.show();
    }
     
    private void DialogProgress(){
        ProgressDialog dialog = ProgressDialog.show(DialogSample.this, "",
                                "잠시만 기다려 주세요 ...", true);
               
        // 창을 내린다.
        // dialog.dismiss();
    }
     
    private void DialogRadio(){
        final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"};
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setIcon(R.drawable.icon);
        alt_bld.setTitle("Select a Phone Model");
        alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item], Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
        AlertDialog alert = alt_bld.create();
        alert.show();
    }
     
    private void DialogSimple(){
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setMessage("Do you want to close this window ?").setCancelable(
                false).setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Action for 'Yes' Button
                    }
                }).setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Action for 'NO' Button
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alt_bld.create();
        // Title for AlertDialog
        alert.setTitle("Title");
        // Icon for AlertDialog
        alert.setIcon(R.drawable.icon);
        alert.show();
    }
     
    private void DialogTimePicker(){
        TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    Toast.makeText(DialogSample.this,
                        "Time is=" + hourOfDay + ":" + minute, Toast.LENGTH_SHORT)
                        .show();
                }
        };
        TimePickerDialog alert = new TimePickerDialog(this, mTimeSetListener, 0, 0, false);
        alert.show();
    }
     
    private void DialogDatePicker(){
        Calendar c = Calendar.getInstance();
        int cyear = c.get(Calendar.YEAR);
        int cmonth = c.get(Calendar.MONTH);
        int cday = c.get(Calendar.DAY_OF_MONTH);
         
        DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
                // onDateSet method
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    String date_selected = String.valueOf(monthOfYear+1)+
                        " /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);
                    Toast.makeText(DialogSample.this,
                            "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
                }
        };
        DatePickerDialog alert = new DatePickerDialog(this,  mDateSetListener,  cyear, cmonth, cday);
        alert.show();
    }
 
}
</string,></string,></string,></map></string,></map></string,></map>




댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday