달력

5

« 2024/5 »

  • 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
728x90
반응형

[android] 날짜와 시간을 위젯으로 입력받기

안녕하세요?
프쟁이 입니다.

이 샘플소스는 안드로이드 설치폴더에 android-sdk-windows/samples/android-8/ApiDemos 위치에 원본소스가 있습니다.

날짜와 시간값을 입력받는 위젯을 버튼을 클릭했을때 입력창을 띄워서,

액티비티 화면에 입력받은 날짜와 시간값을 표시하고 갱신합니다.

먼저 원하시는 패키지 경로에 DateWidgets1.java 액티비티 클래스 파일을 추가합니다.

/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.korsoft.Test022;

import net.korsoft.Test022.R;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.view.View;

import java.util.Calendar;

/**
* Basic example of using date and time widgets, including
* {@link android.app.TimePickerDialog} and {@link android.widget.DatePicker}.
*
* Also provides a good example of using {@link Activity#onCreateDialog},
* {@link Activity#onPrepareDialog} and {@link Activity#showDialog} to have the
* activity automatically save and restore the state of the dialogs.
*
* 날짜와 시간값을 입력받는 위젯을 버튼을 클릭했을때 입력창을 띄워서,
* 입력받은 값으로 날짜와 시간값을 적용합니다.
*/
public class DateWidgets1 extends Activity {

// where we display the selected date and time
private TextView mDateDisplay;

// date and time
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;

static final int TIME_DIALOG_ID = 0;
static final int DATE_DIALOG_ID = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.date_widgets_example_1);

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

Button pickDate = (Button) findViewById(R.id.pickDate);
pickDate.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
//밑에 다이얼로그를 띄우는 메소드에서, DATE_DIALOG_ID
//상수값에 해당되는 다이얼로그를 띄우게 됩니다.
//날짜를 입력받는 위젯을 띄우게 됩니다.
showDialog(DATE_DIALOG_ID);
}
});

Button pickTime = (Button) findViewById(R.id.pickTime);
pickTime.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
//밑에 다이얼로그를 띄우는 메소드에서, TIME_DIALOG_ID
//상수값에 해당되는 다이얼로그를 띄우게 됩니다.
//시간을 입력받는 위젯을 띄우게 됩니다.
showDialog(TIME_DIALOG_ID);
}
});

//초기 날짜값 설정
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);

//변수에 수정된 날짜값을 화면에 갱시표시..
updateDisplay();
}

/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
* 다이얼로그를 생성할때, 두 상수값에 따라서 시간과 날짜 다이얼로그를 생성
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}

/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
* 다이얼로그를 띄우기 전에, 다이얼로그에 표시될 값을 설정합니다.
* 현재 변수값에 있는 날짜와 시간값을 가져와서 위젯 다이얼로그에 설정합니다.
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case TIME_DIALOG_ID:
((TimePickerDialog) dialog).updateTime(mHour, mMinute);
break;
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
break;
}
}

// 위젯 입력다이얼로그에서 입력받은 날짜와 시간값이 변수에 저장이 되엇고,
// 변수에 저장된 날짜와 시간값을 이 메소드에서 텍스트뷰에 갱신하여 표시합니다.
private void updateDisplay() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" ")
.append(pad(mHour)).append(":")
.append(pad(mMinute)));
}

/*
* 날짜입력 위젯에서 설정버튼을 눌렀을때 이벤트 처리를 하고 있습니다.
* 입력받은 값을 파라미터로 가져와서, 변수에 저장하고, 텍스트뷰에 시간값을 갱신합니다.
*/
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();
}
};

/*
* 시간입력 위젯을 띄우고, 값을 입력하고서 설정버튼을 눌렀을때, 이벤트 처리를 합니다.
* 입력받은 시간값을 파라미터로 받아와서, 변수에 저장하고 화면에 시간값을 갱신합니다.
*/
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
updateDisplay();
}
};

/*
* 월/일/분/초를 표시할때 00 두자리 숫자로 표시할때 사용하는 메소드입니다.
*/
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}

레이아웃 xml 파일을, /res/layout/date_widgets_example_1.xml 파일을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="@+id/dateDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/date_widgets_example_dateDisplay_text"/>
</LinearLayout>

<Button android:id="@+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/date_widgets_example_pickDate_text"/>

<Button android:id="@+id/pickTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/date_widgets_example_pickTime_text"/>

</LinearLayout>


문자열 리소스 파일인, /res/values/strings.xml 파일을 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Test022Activity!</string>
<string name="app_name">Test022</string>
<string name="date_widgets_example_dateDisplay_text"></string>
<string name="date_widgets_example_pickTime_text">change the time</string>
<string name="date_widgets_example_pickDate_text">change the date</string>
</resources>


AndroidManifest.xml 파일을 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.korsoft.Test022"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".DateWidgets1" android:label="Views/Date Widgets/1. Dialog">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>

728x90
반응형
:
Posted by mapagilove