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+"分,是好运的开始");
}
}
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> android:layout_width="match_parent" android:layout_height="wrap_content" android:text="选择时间"/> android:layout_width="wrap_content" android:layout_height="300dp" android:id="@+id/datapicket" android:layout_gravity="center_horizontal" android:startYear="2000" android:endYear="2024" android:calendarViewShown="true" android:spinnersShown="true"/> android:layout_width="wrap_content" android:layout_height="300dp" android:layout_gravity="center_horizontal" android:id="@+id/timepicker"/> android:layout_width="match_parent" android:layout_height="wrap_content" android:editable="false" android:cursorVisible="false" android:id="@+id/show"/>