도래울

[Android] Time Picker 본문

개발/Android

[Android] Time Picker

도래울 2016. 2. 5. 11:41

Time Picker

 

시간을 선택하기 위한 위젯을 제공하기 위해서TimePicker 위젯을 사용하며 이것은 사용자가 친숙한 인터페이스로 분을 선택하게 한다.

    여기서 여러분은 TimePickerDialog 만들며이것은 버튼을 눌렀을  floating 다이아로그 박스에 time picker 나타낸다사용자가 시간을 설정할 TextView 새로운 시간을 갱신할 것이다.

 

    1. HelloTimePicker 이름의 새로운 프로젝트를 시작한다.

 

    2. res/layout/main.xml 파일을 열고 다음을 삽입한다:

 

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:orientation="vertical">

    <TextView android:id="@+id/timeDisplay"

                  android:layout_width="wrap_content"

                  android:layout_height="wrap_content"

                  android:text=""/>

    <Button android:id="@+id/pickTime"

                  android:layout_width="wrap_content"

                  android:layout_height="wrap_content"

                  android:text="Change the time"/>

</LinearLayout>

 

    이것은 TextView 가진 기본적인 LinearLayout 만들며 레이아웃은 날짜와 TimePickerDialog 열어줄 Button 출력한다.

 

    3. HelloTimePicker.java 파일을 열고 다음의 클래스 멤버를 클래스에 추가한다:

 

private TextView mTimeDisplay;

private Button mPickTime;

private int mHour;

private int mMinute;

static final int TIME_DIALOG_ID = 0;

 

    이것은 레이아웃 엘리먼트와 시간 필드를 위한 변수를 선언한다TIME_DIALOG_ID 다이아로그를 고유하게 식별하는 정적인 변수이다.

 

    4. 이제 다음의 코드를 onCreate() 메소드에 추가한다:

 

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    // capture our View elements

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

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

    // add a click listener to the button

    mPickTime.setOnClickListener(new View.OnClickListener() {

                  public void onClick(View v) {

                                   showDialog(TIME_DIALOG_ID);

                  }

    });

    // get the current time

    final Calendar c = Calendar.getInstance();

    mHour = c.get(Calendar.HOUR_OF_DAY);

    mMinute = c.get(Calendar.MINUTE);

    // display the current date

    updateDisplay();

}

 

    우선 content view main.xml 설정한다그런 다음에 findViewById(int) 메소드의 반환 레이아웃으로부터 <TextView> <Button> 엘리먼트를 알아낸다Button 위한 새로운 View.OnClickListener 만들어지며버튼을 클릭하였을  이것은 time picker 다이아로그를 위한 고유한 정수 ID 전달하면서 showDialog(int) 메소드를 호출할 것이다showDialog(int) 메소드를 사용하는 것은 activity 다이아로그의 생명 주기를 관리하게 하며또한 이것은 출력되어야  Dialog 요청하기 위해 onCreateDialog(int) 회답 호출 메소드를 호출할 것이다. on-click listener 설정된 다음에현재의 시간과 분을 구하기 위해 새로운 Calendar 만들어진다마지막으로 현재의 날짜를 가진 TextView 채우지 위해 private updateDisplay() 메소드를 호출한다.

 

    5. updateDisplay() pad() 메소드를 추가한다:

 

// updates the time we display in the TextView

private void updateDisplay() {

    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);

}

 

    updateDisplay() 메소드는 시간을 위한 멤버 필드들을 사용하며이들을 TextView(mTimeDisplay) 삽입한다pad() 메소드는 시간과 분에 대한 적절한 스트링 표현을 반환한다.

 

    6. TimePickerDialog.OnTimeSetListener(사용자가 새로운 시간을 설정할  호출됨) 위한 클래스 멤버를 추가한다:

 

// the callback received when the user "sets" the time in the dialog

private TimePickerDialog.OnTimeSetListener mTimeSetListener =

    new TimePickerDialog.OnTimeSetListener() {

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

                                   mHour = hourOfDay;

                                   mMinute = minute;

                                   updateDisplay();

                  }

    };

 

    사용자가 “Set” 버튼을 클릭하여 날짜를 설정할 onTimeSet() 회답 호출 메소드를 호출하며이것은 새로운 시간으로 멤버 필드를 갱신하고 레이아웃의 TextView 갱신한다.

 

    7. 이제 onCreateDialog(int) 회답 호출 메소드를 추가한다:

 

@Override

protected Dialog onCreateDialog(int id) {

    switch (id) {

    case TIME_DIALOG_ID:

                  return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);

    }

    return null;

}

 

    이것은 Activity 회답 호출 메소드이며여러분이 Button on-click listener에서 showDialog(int) 넘겨준 식별자가 이것으로 전달된다. ID 일치할 이것은 onCreate() 메소드의 끝에서 초기화된 멤버 변수와 이전의 단계에서 만들어진 TimePickerDialog.OnTimeSetListener 가지고 TimePickerDialog 초기화한다.

 

    8. 응용프로그램을 실행한다. “Change the time” 버튼을 눌렀을 여러분은 다음의 그림을 보아야 한다:

 

 

 

Comments