Erj*_*jon 9 android android-datepicker material-components material-components-android
我在 Android 中像这样调用 MaterialDatePicker:
MaterialDatePicker.Builder<Pair<Long, Long>> builder = MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
builder.setCalendarConstraints(constraintsBuilder.build());
int dialogTheme = resolveOrThrow(getContext(), R.attr.materialCalendarTheme);
builder.setTheme(dialogTheme);
MaterialDatePicker<?> picker = builder.build();
picker.show(getFragmentManager(), picker.toString());
Run Code Online (Sandbox Code Playgroud)
图书馆是:
dependencies {
implementation 'com.google.android.material:material:1.2.0-alpha01'
}
Run Code Online (Sandbox Code Playgroud)
如何获取此日历的选定日期?我找不到任何听众喜欢onDateSet或OnDateSetListener
Gab*_*tti 21
只需使用在addOnPositiveButtonClickListener用户确认有效选择时调用的侦听器:
对于单个日期选择器:
picker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Long>() {
@Override public void onPositiveButtonClick(Long selection) {
// Do something...
//Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
//calendar.setTimeInMillis(selection);
}
});
Run Code Online (Sandbox Code Playgroud)
对于范围日期选择器:
MaterialDatePicker<Pair<Long, Long>> pickerRange = builderRange.build();
pickerRange.show(....);
pickerRange.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
@Override public void onPositiveButtonClick(Pair<Long,Long> selection) {
Long startDate = selection.first;
Long endDate = selection.second;
//Do something...
}
});
Run Code Online (Sandbox Code Playgroud)
对于那些为此而苦苦挣扎以及他们的时间戳不在一天这一事实的人,这是我的工作解决方案。我需要 API 23,所以我不能在 java.time.* 中使用任何好的 Epoch 函数。对我来说,关键是意识到我需要做时区偏移数学。
picker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Long>() {
@Override
public void onPositiveButtonClick(Long selectedDate) {
// user has selected a date
// format the date and set the text of the input box to be the selected date
// right now this format is hard-coded, this will change
;
// Get the offset from our timezone and UTC.
TimeZone timeZoneUTC = TimeZone.getDefault();
// It will be negative, so that's the -1
int offsetFromUTC = timeZoneUTC.getOffset(new Date().getTime()) * -1;
// Create a date format, then a date object with our offset
SimpleDateFormat simpleFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Date date = new Date(selectedDate + offsetFromUTC);
dataEntry.setText(simpleFormat.format(lDate));
}
});
picker.show(myActivity.getSupportFragmentManager(), picker.toString());
Run Code Online (Sandbox Code Playgroud)
GR Envoy的答案很好,但我想稍微改变一下。最好将时区设置为 UTC。
private val outputDateFormat = SimpleDateFormat("dd.MM.yyyy", Locale.getDefault()).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
...
picker.addOnPositiveButtonClickListener {
val text = outputDateFormat.format(it)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8948 次 |
| 最近记录: |