在Android中,可以使用DatePicker和TimePicker組合來實現時間區間選擇。具體步驟如下:
<DatePicker
android:id="@+id/datePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TimePicker
android:id="@+id/startTimePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TimePicker
android:id="@+id/endTimePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
DatePicker datePicker = findViewById(R.id.datePicker);
TimePicker startTimePicker = findViewById(R.id.startTimePicker);
TimePicker endTimePicker = findViewById(R.id.endTimePicker);
datePicker.setOnDateChangedListener(new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// 獲取用戶選擇的日期
Calendar selectedDate = Calendar.getInstance();
selectedDate.set(year, monthOfYear, dayOfMonth);
}
});
startTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// 獲取用戶選擇的開始時間
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
startTime.set(Calendar.MINUTE, minute);
}
});
endTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// 獲取用戶選擇的結束時間
Calendar endTime = Calendar.getInstance();
endTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
endTime.set(Calendar.MINUTE, minute);
}
});
通過以上步驟,可以實現在Android應用中選擇時間區間的功能。