도래울

Android DatePicker 본문

개발/Android

Android DatePicker

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

Date Picker

 

날짜를 선택하기 위한 위젯을 제공하기 위해서DatePicker 위젯을 사용하며 이것은 사용자가 친숙한 인터페이스로 일자년도를 선택하게 한다.

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

 

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

 

    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/dateDisplay"

                  android:layout_width="wrap_content"

                  android:layout_height="wrap_content"

                  android:text=""/>

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

                  android:layout_width="wrap_content"

                  android:layout_height="wrap_content"

                  android:text="Change the date"/>

</LinearLayout>

 

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

 

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

 

 

private TextView mDateDisplay;

private Button mPickDate;

private int mYear;

private int mMonth;

private int mDay;

static final int DATE_DIALOG_ID = 0;

 

    첫번째 멤버 그룹은 레이아웃 View 날짜 아이템을 위한 변수를 정의한다DATE_DIALOG_ID 정적인 변수이며이것은 date picker 출력할 Dialog 고유하게 식별한다.

 

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

 

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    // capture our View elements

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

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

    // add a click listener to the button

    mPickDate.setOnClickListener(new View.OnClickListener() {

                  public void onClick(View v) {

                                   showDialog(DATE_DIALOG_ID);

                  }

    });

    // get the current date

    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)

    updateDisplay();

}

 

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

 

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

 

// updates the date in the TextView

private void updateDisplay() {

    mDateDisplay.setText(

                  new StringBuilder()

                                   // Month is 0 based so add 1

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

                                   .append(mDay).append("-")

                                   .append(mYear).append(" "));

}

 

     메소드는 레이아웃의 TextView(mDateDisplay) 날짜를 쓰기 위해 클래스에 대해 선언된 멤버 날짜 값을 사용하며 값은 위에서 선언되고 초기화되었다.

 

    6. 새로운 DatePickerDialog.OnDateSetListener HelloDatePicker 클래스의 멤버로 초기화한다:

 

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

private DatePickerDialog.OnDateSetListener mDateSetListener =

    new DatePickerDialog.OnDateSetListener() {

                  public void onDateSet(DatePicker view, int year,

                                                        int monthOfYear, int dayOfMonth) {

                                   mYear = year;

                                   mMonth = monthOfYear;

                                   mDay = dayOfMonth;

                                   updateDisplay();

                  }

    };

 

    DatePickerDialog.OnDateSetListener 사용자가 “Set” 버튼을 클릭하여 날짜를 설정할  반응한다 시간에 onDateSet() 회답 호출 메소드를 호출하며이것은 새로운 날짜로 mYearmMonthmDay 멤버 필드를 갱신하고 그런 다음에 TextView 갱신하기 위해 private updateDisplay() 메소드를 호출하도록 정의한다.

 

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

 

@Override

protected Dialog onCreateDialog(int id) {

    switch (id) {

    case DATE_DIALOG_ID:

                  return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);

    }

    return null;

}

 

    이것은 Activity 회답 호출 메소드이며showDialog(int)(Button View.OnClickListener 호출하는 메소드) 넘겨준 정수 ID 이것으로 전달된다. ID 여기서 정의한 switch case 일치할 날짜를 초기화하는 날짜 변수와 이전의 단계에서 만들어진 DatePickerDialog.OnDateSetListener 가지고 DatePickerDialog 객체가 만들어진다.

 

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

 

 

 

Comments