欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android中DatePicker和TimePicker的使用方法详解

程序员文章站 2023-02-02 12:12:39
本文以实例讲述了android中datepicker和timepicker的使用方法,具体步骤如下: 下面是实现具体功能的代码,其中main.xml代码为: &...

本文以实例讲述了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 + "分");

 }
}

运行效果如下图所示:

android中DatePicker和TimePicker的使用方法详解