android 日期与时间选择控件用法

作者:袖梨 2022-06-25

timepicker也继承自framelayout类。时间选择控件向用户显示一天中的时间(可以为24小时,也可以为am/pm制),并允许用户进行选择。如果要捕获用户修改时间数据的事件,便需要为timepicker添加ontimechangedlistener监听器

以下模拟日期与时间选择控件的用法
目录结构
main.xml布局文件

android:orientation="vertical"
android:layout_
android:layout_>
android:layout_
android:layout_
android:layout_gravity="center_horizontal"/>
android:layout_
android:layout_
android:cursorvisible="false"
android:editable="false"/>
android:layout_
android:layout_
android:layout_gravity="center_horizontal"/>
android:layout_
android:layout_
android:cursorvisible="false"
android:editable="false"/>
dptpactivity类
package com.ljq.activity;

import java.util.calendar;

import android.app.activity;
import android.os.bundle;
import android.widget.datepicker;
import android.widget.edittext;
import android.widget.timepicker;
import android.widget.datepicker.ondatechangedlistener;
import android.widget.timepicker.ontimechangedlistener;

public class dptpactivity extends activity {
private edittext dateet=null;
private edittext timeet=null;

@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
dateet=(edittext)findviewbyid(r.id.dateet);
timeet=(edittext)findviewbyid(r.id.timeet);
datepicker datepicker=(datepicker)findviewbyid(r.id.datepicker);
timepicker timepicker=(timepicker)findviewbyid(r.id.timepicker);

calendar calendar=calendar.getinstance();
int year=calendar.get(calendar.year);
int monthofyear=calendar.get(calendar.month);
int dayofmonth=calendar.get(calendar.day_of_month);
datepicker.init(year, monthofyear, dayofmonth, new ondatechangedlistener(){

public void ondatechanged(datepicker view, int year,
int monthofyear, int dayofmonth) {
dateet.settext("您选择的日期是:"+year+"年"+(monthofyear+1)+"月"+dayofmonth+"日。");
}

});

timepicker.setontimechangedlistener(new ontimechangedlistener(){

public void ontimechanged(timepicker view, int hourofday, int minute) {
timeet.settext("您选择的时间是:"+hourofday+"时"+minute+"分。");
}

});
}
}
运行结果

相关文章

精彩推荐