时间:2020-11-29 10:59:58 | 栏目:Android代码 | 点击:次
本文以实例讲述了android中DatePicker和TimePicker的使用方法,具体步骤如下:
下面是实现具体功能的代码,其中main.xml代码为:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请选择购买本书的具体时间" /> <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> <EditText android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:cursorVisible="false" android:editable="false" /> </LinearLayout>
java代码为:
public class AndroidDemo5Activity extends Activity { // 记录当前的时间 private int year; private int month; private int day; private int hour; private int minute; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); DatePicker date = (DatePicker) findViewById(R.id.datePicker); TimePicker time = (TimePicker) findViewById(R.id.timePicker); // 或许当前的年月日,小时,分钟 Calendar ca = Calendar.getInstance(); year = ca.get(Calendar.YEAR); month = ca.get(Calendar.MONTH); day = ca.get(Calendar.DAY_OF_MONTH); hour = ca.get(Calendar.HOUR); minute = ca.get(Calendar.MINUTE); // 初始化DatePicker date.init(year, month, day, new OnDateChangedListener() { @Override public void onDateChanged(DatePicker arg0, int year, int month, int day) { AndroidDemo5Activity.this.year = year; AndroidDemo5Activity.this.month = month; AndroidDemo5Activity.this.day = day; // 显示当前时间和日期 showDate(year, month, day, hour, minute); } }); // 为TimerPicker指定事件监听器 time.setOnTimeChangedListener(new OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker arg0, int hour, int minute) { AndroidDemo5Activity.this.hour = hour; AndroidDemo5Activity.this.minute = minute; } }); } protected void showDate(int year2, int month2, int day2, int hour2, int minute2) { EditText text = (EditText) findViewById(R.id.show); text.setText("您的购买时间为:" + year2 + "年" + month2 + "月" + day2 + "日" + hour2 + "时" + minute2 + "分"); } }
运行效果如下图所示: