简介
下面以一个让用户选择日期、时间的例子来示范DatePicker和TimePicker的功能和用法
step1:新建一个项目DateAndTimePicker
step2:编写应用的UI界面 /layout/main.xml
step3:主程序MainActivity.java
package cn.roco.picker;import java.util.Calendar;import android.app.Activity;import android.os.Bundle;import android.widget.DatePicker;import android.widget.DatePicker.OnDateChangedListener;import android.widget.EditText;import android.widget.TimePicker;import android.widget.TimePicker.OnTimeChangedListener;public class MainActivity extends Activity { private int year; private int month; private int day; private int hour; private int minute; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker); TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker); Calendar calendar = Calendar.getInstance(); year = calendar.get(Calendar.YEAR); month = calendar.get(Calendar.MONTH); day = calendar.get(Calendar.DAY_OF_MONTH); hour = calendar.get(Calendar.HOUR); minute = calendar.get(Calendar.MINUTE); datePicker.init(year, month, day, new OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int month, int day) { MainActivity.this.year = year; MainActivity.this.month = month; MainActivity.this.day = day; // 显示时间 showDate(year, month, day, hour, minute); } }); timePicker.setOnTimeChangedListener(new OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hour, int minute) { MainActivity.this.hour = hour; MainActivity.this.minute = minute; // 显示时间 showDate(year, month, day, hour, minute); } }); } private void showDate(int year, int month, int day, int hour, int minute) { EditText show = (EditText) findViewById(R.id.show); show.setText("您的购买日期为:" + year + "年" + month + "月" + day + "日 " + hour + "时" + minute + "分 "); }}
step4:部署应用到模拟器上,并选择日期和时间
==================================================================================================
作者:欧阳鹏 欢迎转载,与人分享是进步的源泉!
转载请保留原文地址:
==================================================================================================