본문 바로가기
안드로이드

Android – Dialog, AlertDialog, ProgressDialog, DatePickerDialog, TimePickerDialog

by 호군 2011. 4. 26.
반응형
링크 : http://muritzy.wordpress.com/2010/10/13/android-dialog-alertdialog-progressdialog-datepickerdialog-timepickerdialog/

원문에 가시면, 샘플소스코드도 제공하고있습니다.


Android에서 사용하는 Dialog에 대해서 알아보도록 하겠습니다.

[참고자료]
메인글 – 앞부분 설명은 아래 원문을 번역한 글입니다.
http://developer.android.com/guide/topics/ui/dialogs.html
DatePickerDialog Source 참조.
http://developer.android.com/resources/tutorials/views/hello-datepicker.html
TimePickerDialog Source 참조.
http://developer.android.com/resources/tutorials/views/hello-timepicker.html
Dialog는 보통 현 Activity 앞에 보여지는 작은 윈도우입니다. 많은 경우 새로운 Activity를 띄워 서로 데이터를 주고 받기 보다는 Dialog를 사용한다면 좀 더 편리하게 Android 개발을 할 수 있습니다.

먼저 Dialog 및 AlertDialog의 기본 기능을 살펴 본 후 다음 Post에서 Custom Dialog를 만들어 보도록 하겠습니다.

Dialog 하위 클래스에는 다음과 같은 특수한 Dialog가 존재합니다
AlertDialog : 대부분의 Dialog UI를 제공함.
ProgressDialog : Progress Wheel 이나 progress Bar 기능 지원
DatePickerDialog : 날짜 선택
TimePickereDialog : 시간 선택
Showing a Dialog

Dialog는 항상 Activity의 일부로 생성되어 보여집니다. 보통은 Activity 내부의 onCreateDialog(int) Callback Method 안에서 Dialog를 생성하는데, 이 Callback 메소드를 사용해서 Dialog를 생성하면 Android는 각각의 Dialog의 상태를 자동으로 관리하고, 호출된 Dialog의 소유자로 호출한 Activity가 자동으로 지정됩니다.
Dialog의 소유자 Activity가 지정되면, Dialog는 Activity로부터 Properties를 상속 받을 수 있습니다. 예를 들어 Dialog가 Open 되었을때 Menu Key는 Activity에 정의되어 있는 Option menu를 보여주며, Volumn Key는 Activity에 의해 사용되는 Audio Stream을 조절 할 수 있습니다.
(* 이 부분은 저로서도 명확하게 이해하기가 어렵군요. Menu 부분은 테스트를 해 봤는데, 별로 차이점을 찾지 못했구요. 좀 더 다른 테스트를 더 해봐야 할 듯 합니다.)
Note: 만일 onCreateDialog(int) 메소드 외부에서 Dialog를 생성하면 Activity에 붙어지지 않게 됩니다만, setOwnerActivity(Activity)를 통해 Activity에 Dialog를 붙일 수도 있습니다.
Dialog를 보여주고 싶다면 showDialog(int)를 호출하고 보여주고 싶은 Dialog를 구분해주는 번호를 넘겨주면 됩니다.

Dialog가 처음 요청 받게 되면, Android는 onCreateDialog(int)를 호출하는데 그곳에서 Dialog를 인스턴스를 생성해야 합니다. onCreateDialog(int) Callback Method는 showDialog(int)로 받은 것과 동일한 ID를 넘겨받아 Dialog를 생성한 후 Method의 맨 끝에서 해당 Object를 리턴합니다.

Dialog가 보여지기 이전에, Android는 선택적 Callback Method인 onPrepareDialog(int, Dialog)를 호출합니다. 만일 Dialog가 열릴 때 Dialog의 Property를 바꾸고 싶다면 onPrepareDialog Method를 재정의 해야 합니다. onPrepareDialog Method는 Dialog가 열릴 때마다 호출되는 되지만, onCreateDialog(int)는 Dialog가 처음 열릴 때 한번 만 호출됩니다.
만일 onPrepareDialog()를 정의하지 않았다면 Dialog는 이전 상태를 그대로 유지합니다. onPrepareDialog Method는 onCreateDialog()를 통해 만들어진 Dialog Object와 함께 Dialog의 ID를 인자로 넘겨 받습니다.

onCreateDialog(int)와 onPrepareDialog(int, Dialog) Callback Methods구현은 일반적으로 인자로 넘겨받는 ID값을 체크하여 처리하는 swith 구문을 사용하는 것이 일반적입니다.
Dialog 관련 코딩 작성 스타일을 보겠습니다.
먼저, 각각의 Dialog에 대한 ID를 정의한다.

static final int DIALOG_PAUSED_ID = 0;

static final int DIALOG_GAMEOVER_ID = 1;

그 이후, onCreateDialog(int) Callback을 정의합니다.

protected Dialog onCreateDialog(int id) {

Dialog dialog;

switch(id) {

case DIALOG_PAUSED_ID:

// do the work to define the pause Dialog

break;

case DIALOG_GAMEOVER_ID:

// do the work to define the game over Dialog

break;

default:

dialog = null;

}

return dialog;

}

Dismissing a Dialog

Dialog를 닫고 싶을 때 Dialog Object에서 dismiss()를 호출하여 종료시킬 수 있으며 필요시 dismissDialog(int)를 호출할 수 있습니다.

Dialog의 State 관리를 위해 onCreateDialog(int)를 사용한다면 Dialog가 닫힐때마다 Dialog Object의 State은 Activity에 의해 유지됩니다. 만일 생성한 Object가 더이상 필요없거나 State가 Clear되는 것이 중요하다면 removeDialog(int)를 호출하면 됩니다. removeDialog() 메소드를 호출하면 Object에 연결된 모든 내부 참조를 삭제하며 만일 Dialog가 현재 보여지고 있으면 닫아주게 됩니다.

Using Dismiss Listeners

만약 Dialog가 닫히는 그 시점에 Appliction이 특정 기능을 수행하도록 처리하려면 Dialog에 on-dismiss listener를 구현해야 합니다.

먼저 DialogInterface.onDismissListener Interface를 정의합니다. 이 Interface는 onDismiss(DialogInterface) Method 하나를 가지고 있으며 Dialog가 닫힐 때 호출됩니다. 그 다음 setOnDismissListener()에 구현된 OnDismissListener를 넘겨주면 됩니다..

Dialog가 닫히는 동작이 dismiss 메소드가 호출될 때 말고도 Cancel에 의해서도 일어날 수 있는 점을 알아야 합니다. 사용자가 "back" Key를 눌렀을 때나 Dialog내에 있는 Cancel 버튼으로 cancel()이 호출되었을 때 발생하게 합니다. Dialog가 취소되었을 때 OnDismissListener은 알림을 기다리게 되지만 Dialog가 명시적으로 취소 되었음을 알려주고 싶다면 setOnCancelListen()를 DialogInterface.OnCancelListener로 등록시켜야 합니다.
Creating an AlertDialog

AlertDialog는 Dialog Class의 하위 클래스로 가장 많이 사용하는 Dialog 타입입니다.
기본적으로 Title, Text Message, One, Two, or Three Buttons, List of Selectable Itmes (check box or Raido Button) 을 가진 Dialog 이면 AlertDialog를 사용하시면 됩니다.
AlertDialog를 생성하려면 AlertDialog.Builder subclass를 사용합니다. AlertDialog.Builder(Context)를 통해 Builder를 얻어와 AlertDialog Properties를 설정한 후  create()을 통해 AlertDialog Object를 얻어온다.

샘플 코드를 보겠습니다.
AlertDialog Sample1

protected Dialog onCreateDialog(int id) {

Dialog dialog;

AlertDialog.Builder builder;

switch(id) {

case DIALOG_SIMPLE1:

builder = new AlertDialog.Builder(this);

builder.setMessage("Are you sure you want to exit?")

.setCancelable(false)

.setPositiveButton("Yes", newDialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

MainActivity.this.finish();

}

})

.setNegativeButton("No", newDialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

dialog.cancel();

}

});

dialog = builder.create();

break;

default :

dialog = null;

}

return dialog;

}

위 그림처럼 두개의 버튼을 가지는 Dialog를 만들기 위해서 AlertDialog.Builder 인스턴스에 set..Button 메소드를 사용해서 버튼을 지정하고, 버튼 클릭시 처리 내용을 기술하면 됩니다.
setCancelable(false)로 지정하면 Dialog가 실행된 상태에서 취소 버튼을 클릭해도 화면이 취소(사라지지) 않습니다.
AlertDialog Sample3 – List Style

//array xml에서 불러옴.

final String[] colors = getResources().getStringArray(R.array.colors);

builder = new AlertDialog.Builder(this);

builder.setTitle("Pick a color");

builder.setItems(colors, new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), colors[item], Toast.LENGTH_SHORT).show();

}

});

dialog = builder.create();

Array 데이터는 res\values\array.xml로 다음과 같이 정의해서 사용했습니다

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string-array name="colors">

<item>Red</item>

<item>Green</item>

<item>Yellow</item>

<item>White</item>

</string-array>

</resources>

List형의 AlertDialog는 setItmes 메소드로 배열정보와 항목 클릭시 코드를 기술하면 됩니다. 리스트 항목 선택시 별도로 dialog를 dismiss() 하지 않아도 자동으로 Dialog가 닫기는 군요.
AlertDialog Sample4 – CheckBox

final CharSequence[] items = {"Red", "Green","Blue"};

final boolean[] states = {false, false, true};

builder = new AlertDialog.Builder(this);

builder.setTitle("Pick a color");

//setMultiChoiceItems(int itemsId, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)

builder.setMultiChoiceItems(items, states, new DialogInterface.OnMultiChoiceClickListener() {

@Override

public void onClick(DialogInterface dialog, int item, boolean state) {

Toast.makeText(getApplicationContext(), items[item] + " set to " + state, Toast.LENGTH_SHORT).show();

//자동으로 닫기지는 않는다.

}

});

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

String msg = "";

for(boolean state : states) {

msg += String.valueOf(state) + " ";

}

Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();

}

});

dialog = builder.create();

CheckBox 리스트를 가진 Dialog를 만들기 위해서는 리스트에 뿌릴 배열(items) 및 각 항목의 체크여부를 가진 Boolean[] 배열 변수가 필요합니다.
Builder.setMultiChoiceItmes 메소드에 두 배열 변수 및 DialogInterface.OnMultiChoiceClickListener 인터페이스를 정의하면 됩니다.
각 항목이 선택되거나 해제될 때 마다 states  boolean 배열 변수의 값이 자동으로 설정되므로, Dialog 창이 닫길 때 해당 정보를 읽어서 다른 처리하고자 한다면 states 배열을 읽어서 처리하면 됩니다.
AlertDialog Sample5 – Radio Button

final CharSequence[] items1 = {"Red", "Green","Blue"};

builder = new AlertDialog.Builder(this);

builder.setTitle("Pick a color");

//setSingleChoiceItems(CharSequence[] items, int checkedItem, DialogInterface.OnClickListener listener)

builder.setSingleChoiceItems(items1, 0, new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), items1[item] , Toast.LENGTH_SHORT).show();

//자동으로 닫기지 않는다.

dialog.dismiss();

}

});

dialog = builder.create();

Radio Button은 CheckBox과 코드 스타일이 비슷합니다. setMultiChoiceItems() 메소드 대신 setSingleChoiceItems 메소드로 항목을 지정하면 됩니다.
setSingleChoiceItems 메소드의 두번째 파라미터는 checkedItem 항목을 지정하는 변수로 지정된 인덱스를 가진 Radio Button이 선택되어 표시됩니다.
Radio Button 선택시 자동으로 Dialog 창이 닫기지 않아 dismiss() 코드를 onClick 이벤트에 추가했습니다.
ProgressDialog – Circle


ProgressDialog는 위 그림처럼 Spinning Wheel의 형태로 애니메이션 프로그레스를 보여줄 수 도 있으며, 아래 그림처럼 정해진 진행과정을 가지는 Task를 위해 Progress Bar의 형태로 보여줄 수도 있습니다. Progress Dialog를 여는 것은 간단하게 ProgressDialog.show()만 호출하면 됩니다.

저는 onCreateDialog Callback 내에서 dialog를 생성했으며,

case DIALOG_PROGRESS1:

dialog = ProgressDialog.show(MainActivity.this, "", "Loading, Please Wait..", true, true);

버튼 클릭시 ProgressDialog롤 보여주고, 5초가 지나면 자동으로 닫기도록 Sample 코드를 작성했습니다.

progressDialog1 = (Button)findViewById(R.id.progressDialog1);

progressDialog1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_PROGRESS1);

TimerTask myTask = new TimerTask(){

public void run(){

dismissDialog(DIALOG_PROGRESS1);

}

};

Timer timer = new Timer();

timer.schedule(myTask, 5000);

}

});

ProgressDialog – Bar

애니메이션 형태의 Progress Bar를 보여주기 위해서는 :
1. ProgressDialog(Context) 생성자를 통해 ProgressDialog를 초기화 한다.
2. setProgressStyle(int)를 통해 "STYLE_HORIZONTAL"로 Style을 설정하고 그런 메시지를 이용하여 다른 Properties도 설정한다.
3. Dialog를 보여줄 준비기 되었다면, show()를 호출하거나 onCreateDialog(int) Callback을 통해 ProgressDialog를 반환시켜 준다.
4. 전체 진행 과정이 완료되기 까지 setProgress(int)를 호출하여 Bar에 보여지는 상태 진행정도를 증가 시킬수 있으며 incrementProgressBy(int)를 통해서도 가능하다.

dialog = new ProgressDialog(MainActivity.this);

((ProgressDialog)dialog).setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

((ProgressDialog)dialog).setMessage("Loading..");

((ProgressDialog)dialog).setCancelable(true);

progressDialog = (ProgressDialog)dialog;

일반적으로 Bar 형태의 Progress는 별도 Thread를 생성해 다른 처리를 하면서 진행상태를 표시하기 위해 사용합니다. onCreateDialog() 메소드 내에서 dialog 지역변수 값을 progressDialog 멤버변수에 할당하여 Thread내에서 progressDialog 값을 증가시키도록 테스트 코드를 작성했습니다.

//ProgressBar 값을 증가시키는 Handler
Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

int total = msg.getData().getInt("total");

progressDialog.setProgress(total);

if(total >= 100) {

progressDialog.dismiss();

}

}

};

//OnCreate() 메소드 내에 버튼 클릭시 ProgressBar를 보여주고, 값을 증가시키는 Thread 생성 코드

progressDialog2 = (Button)findViewById(R.id.progressDialog2);

progressDialog2.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_PROGRESS2);

new Thread(new Runnable() {

@Override

public void run() {

try {

for(int i = 0; i <= 100; i++) {

Thread.sleep(100);

Message msg = handler.obtainMessage();

Bundle b = new Bundle();

b.putInt("total", i);

msg.setData(b);

handler.sendMessage(msg);

}

} catch(Throwable t) {

}

}

}).start();

}

});

DatePickerDialog

DatePickerDialog와 TimePickerDialog는 onCreateDialog() 메소드내에서 DatePickerDialog 혹은 TimePickerDialog 인스턴스를 생성해 리턴하면 됩니다.

생성자에서 사용자가 날짜 설정시 처리할 Callback Method인 DatePickerDialog.OnDateSetListener 를 먼저 구현한 다음 파라미터로 함게 넘겨주면 쉽게 호출 할 수 있습니다.

private DatePickerDialog.OnDateSetListener mDateSetListener = newDatePickerDialog.OnDateSetListener() {

@Override

public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {

mYear = year;

mMonth = monthOfYear;

mDay = dayOfMonth;

updateDateDisplay();

}

};

//OnCreateDialog() 메소드 내에서
case
DIALOG_DATEPICKER:

dialog = new DatePickerDialog(MainActivity.this, mDateSetListener ,mYear, mMonth, mDay);

TimePickerDialog

TimePickerDialog는 DatePickerDialog과 거의 코드가 유사합니다. 생성자로 인스턴스 생성시에 24시간제인지? 12시간제인지를 지정할 수 있습니다. 소스는 아래 전체 코드를 보시기 바랍니다.

public class MainActivity extends Activity {

//Dialog 호출을 위한 상수 정의

static final int DIALOG_SIMPLE1 = 0;

static final int DIALOG_SIMPLE2 = 1;

static final int DIALOG_LIST = 3;

static final int DIALOG_CHECKBOX = 4;

static final int DIALOG_RADIO = 5;

static final int DIALOG_PROGRESS1 = 6;

static final int DIALOG_PROGRESS2 = 7;

static final int DIALOG_DATEPICKER = 8;

static final int DIALOG_TIMEPICKER = 9;

public static final int MENU_INFO = Menu.FIRST;

Button simpleAlertDialog1;

Button simpleAlertDialog2;

Button listAlertDialog;

Button checkboxAlertDialog;

Button radioAlertDialog;

Button progressDialog1;

Button progressDialog2;

ProgressDialog progressDialog;

//DatePickerDialog

private TextView mDateDisplay;

private Button mPickDate;

private int mYear;

private int mMonth;

private int mDay;

//TimePickerDialog

private TextView mTimeDisplay;

private Button mPickTime;

private int mHour;

private int mMinute;

Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

int total = msg.getData().getInt("total");

progressDialog.setProgress(total);

if(total >= 100) {

progressDialog.dismiss();

}

}

};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

simpleAlertDialog1 = (Button)findViewById(R.id.simpleAlertDialog1);

simpleAlertDialog1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_SIMPLE1);

}

});

simpleAlertDialog2 = (Button)findViewById(R.id.simpleAlertDialog2);

simpleAlertDialog2.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showSimpleDialog();

}

});

listAlertDialog = (Button)findViewById(R.id.listAlertDialog);

listAlertDialog.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_LIST);

}

});

checkboxAlertDialog = (Button)findViewById(R.id.checkboxAlertDialog);

checkboxAlertDialog.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_CHECKBOX);

}

});

radioAlertDialog = (Button)findViewById(R.id.radioAlertDialog);

radioAlertDialog.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_RADIO);

}

});

progressDialog1 = (Button)findViewById(R.id.progressDialog1);

progressDialog1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_PROGRESS1);

TimerTask myTask = new TimerTask(){

public void run(){

dismissDialog(DIALOG_PROGRESS1);

}

};

Timer timer = new Timer();

timer.schedule(myTask, 5000);

}

});

progressDialog2 = (Button)findViewById(R.id.progressDialog2);

progressDialog2.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_PROGRESS2);

new Thread(new Runnable() {

@Override

public void run() {

try {

for(int i = 0; i <= 100; i++) {

Thread.sleep(100);

Message msg = handler.obtainMessage();

Bundle b = new Bundle();

b.putInt("total", i);

msg.setData(b);

handler.sendMessage(msg);

}

} catch(Throwable t) {

}

}

}).start();

}

});

//DatePicker Dialog Test

mDateDisplay = (TextView) findViewById(R.id.dateDisplay);

mPickDate = (Button) findViewById(R.id.pickDate);

mPickDate.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_DATEPICKER);

}

});

// 현재 날짜를 가져온다.

final Calendar c = Calendar.getInstance();

mYear = c.get(Calendar.YEAR);

mMonth = c.get(Calendar.MONTH);

mDay = c.get(Calendar.DAY_OF_MONTH);

// display the current date (this method is below)

updateDateDisplay();

//TimePicker Dialog Test

mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);

mPickTime = (Button) findViewById(R.id.pickTime);

mPickTime.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DIALOG_TIMEPICKER);

}

});

final Calendar c1 = Calendar.getInstance();

mHour = c1.get(Calendar.HOUR_OF_DAY);

mMinute = c1.get(Calendar.MINUTE);

updateTimeDisplay();

}

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog;

AlertDialog.Builder builder;

switch(id) {

case DIALOG_SIMPLE1:

builder = new AlertDialog.Builder(this);

builder.setMessage("Are you sure you want to exit?")

.setCancelable(false)

.setPositiveButton("Yes", newDialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, intid) {

MainActivity.this.finish();

}

})

.setNegativeButton("No", newDialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, intid) {

dialog.cancel();

}

});

dialog = builder.create();

break;

case DIALOG_LIST:

//array xml에서 불러옴.

final String[] colors = getResources().getStringArray(R.array.colors);

builder = new AlertDialog.Builder(this);

builder.setTitle("Pick a color");

builder.setItems(colors, newDialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), colors[item], Toast.LENGTH_SHORT).show();

}

});

dialog = builder.create();

break;

case DIALOG_CHECKBOX:

final CharSequence[] items = {"Red", "Green","Blue"};

final boolean[] states = {false, false, true};

builder = new AlertDialog.Builder(this);

builder.setTitle("Pick a color");

//setMultiChoiceItems(int itemsId, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)

builder.setMultiChoiceItems(items, states, newDialogInterface.OnMultiChoiceClickListener() {

@Override

public void onClick(DialogInterface dialog, int item,boolean state) {

Toast.makeText(getApplicationContext(), items[item] + " set to " + state, Toast.LENGTH_SHORT).show();

//자동으로 닫기지는 않는다.

}

});

builder.setPositiveButton("OK", newDialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

String msg = "";

for(boolean state : states) {

msg += String.valueOf(state) + " ";

}

Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();

}

});

dialog = builder.create();

break;

case DIALOG_RADIO:

final CharSequence[] items1 = {"Red", "Green","Blue"};

builder = new AlertDialog.Builder(this);

builder.setTitle("Pick a color");

//setSingleChoiceItems(CharSequence[] items, intcheckedItem, DialogInterface.OnClickListener listener)

builder.setSingleChoiceItems(items1, 0, newDialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), items1[item] , Toast.LENGTH_SHORT).show();

//자동으로 닫기지 않는다.

dialog.dismiss();

}

});

dialog = builder.create();

break;

case DIALOG_PROGRESS1:

dialog = ProgressDialog.show(MainActivity.this, "","Loading, Please Wait..", true, true);

break;

case DIALOG_PROGRESS2:

dialog = new ProgressDialog(MainActivity.this);

((ProgressDialog)dialog).setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

((ProgressDialog)dialog).setMessage("Loading..");

((ProgressDialog)dialog).setCancelable(true);

progressDialog = (ProgressDialog)dialog;

break;

case DIALOG_DATEPICKER:

dialog = new DatePickerDialog(MainActivity.this,mDateSetListener , mYear, mMonth, mDay);

break;

case DIALOG_TIMEPICKER:

dialog = new TimePickerDialog(MainActivity.this,mTimeSetListener, mHour, mMinute, true);

break;

default :

dialog = null;

}

return dialog;

}

private DatePickerDialog.OnDateSetListener mDateSetListener = newDatePickerDialog.OnDateSetListener() {

@Override

public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {

mYear = year;

mMonth = monthOfYear;

mDay = dayOfMonth;

updateDateDisplay();

}

};

private TimePickerDialog.OnTimeSetListener mTimeSetListener = newTimePickerDialog.OnTimeSetListener() {

@Override

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

mHour = hourOfDay;

mMinute = minute;

updateTimeDisplay();

}

};

private void showSimpleDialog() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Are you sure you want to exit?")

.setCancelable(false)

.setPositiveButton("Yes", newDialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

MainActivity.this.finish();

}

})

.setNegativeButton("No", newDialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

dialog.cancel();

}

});

builder.show();

}

private void updateDateDisplay() {

mDateDisplay.setText(

new StringBuilder()

.append(mYear).append("-")

.append(mMonth + 1).append("-")

.append(mDay));

}

private void updateTimeDisplay() {

mTimeDisplay.setText(

new StringBuilder()

.append(pad(mHour)).append(":")

.append(pad(mMinute)));

}

private static String pad(int c) {

if (c >= 10)

return String.valueOf(c);

else

return "0" + String.valueOf(c);

}

반응형