当前位置:网站首页>datepicket和timepicket,日期、时间选择器的功能和用法

datepicket和timepicket,日期、时间选择器的功能和用法

2022-07-07 15:40:00 XLMN

datepicket和timepicket,日期、时间选择器的功能和用法
两者都是从framelayout派生来的,datepicket供用户选择日期,timepicket供用户选择时间

datapicket通过ondatechangedlistener进行监听,timepicket通过添加ontimerchangedlistener进行监听

public class MainActivity extends Activity {
// 定义5个记录当前时间的变量
private int year;
private int month;
private int day;
private int hour;
private int minute;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.picket);;
    DatePicker dp=findViewById(R.id.datapicket);
    TimePicker tp=findViewById(R.id.timepicker);
    //获取当前的年月日小时分钟
    Calendar ca=Calendar.getInstance();
    year=ca.get(Calendar.YEAR);
    month=ca.get(Calendar.MONTH);
    day=ca.get(Calendar.DATE);
    hour=ca.get(Calendar.HOUR);
    //初始化DATApicker组件,初始化时指定监听器
    dp.init(year, month, day, new DatePicker.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指定监听器
    tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
        @Override
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            MainActivity.this.hour=hourOfDay;
            MainActivity.this.minute=minute;
            //显示当前日期时间
            showDate(year,month,day,hour,minute);
        }
    });
}
private void showDate(int year,int month,int day ,int hour,int minute) {
    EditText et=findViewById(R.id.show);
    et.setText("现在的日期是:"+year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分,是好运的开始");
}

}

<?xml version="1.0" encoding="utf-8"?>




<TimePicker
    android:layout_width="wrap_content"
    android:layout_height="300dp"
    android:layout_gravity="center_horizontal"
    android:id="@+id/timepicker"/>
<!--显示用户输入日期时间的控件-->
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:editable="false"
    android:cursorVisible="false"
    android:id="@+id/show"/>

在这里插入图片描述

原网站

版权声明
本文为[XLMN]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44701192/article/details/125075395