您好,我正在日期选择器对话框中传递月份和年份以显示该月的日期,是否有任何可能的方式从日期选择器对话框中隐藏年份和月份This is how it looks
这是我需要显示的内容:
答案 0 :(得分:0)
您要使用CalendarView
小部件。请注意,年和月将显示,但不会以大字体显示。您可以将其放入带有一些按钮的DialogFragment中,以实现所需的结果:
public class CalendarViewDialog extends DialogFragment {
private static final String KEY_DATE = "date";
private long date = System.currentTimeMillis();
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Context context = requireContext();
Bundle args = getArguments();
if (args != null && args.containsKey(KEY_DATE)) {
date = args.getLong(KEY_DATE);
}
CalendarView calendarView = new CalendarView(context);
calendarView.setDate(date);
calendarView.setOnDateChangeListener((view, year, month, dayOfMonth) ->
date = new GregorianCalendar(year, month, dayOfMonth).getTimeInMillis());
return new AlertDialog.Builder(context)
.setView(calendarView)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
if (getParentFragment() instanceof Callback) {
((Callback) requireParentFragment()).onDateSelected(date);
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
public static CalendarViewDialog newInstance(long date) {
CalendarViewDialog dialog = new CalendarViewDialog();
Bundle args = new Bundle();
args.putLong(KEY_DATE, date);
dialog.setArguments(args);
return dialog;
}
public interface Callback {
void onDateSelected(long date);
}
}
在另一个片段中像这样使用它:
public class MyFragment extends Fragment implements CalendarViewDialog.Callback {
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
btn.setOnClickListener(v -> {
CalendarViewDialog.newInstance(System.currentTimeMillis())
.show(getChildFragmentManager(), "date-dialog");
});
}
@Override
public void onDateSelected(long date) {
// Do whatever you want with `date`.
}
}
答案 1 :(得分:0)
您可以使用材料成分库提供的MaterialDatePicker
。
除了隐藏月份/年份选择器之外,您还可以使用CalendarConstraints
将选择限制为一个月。
long today = MaterialDatePicker.todayInUtcMilliseconds();
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
utc.clear();
utc.setTimeInMillis(today);
utc.set(Calendar.DAY_OF_MONTH, 1);
long thisMonthFirst = utc.getTimeInMillis();
utc.set(Calendar.DATE, utc.getActualMaximum(Calendar.DATE));
long thisMonthLast = utc.getTimeInMillis();
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
builder.setSelection(today);
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
constraintsBuilder.setOpenAt(today);
constraintsBuilder.setStart(thisMonthFirst);
constraintsBuilder.setEnd(thisMonthLast);
builder.setCalendarConstraints(constraintsBuilder.build());
MaterialDatePicker<Long> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());
通过这种方式,选择仅限于当前月份,并且用户无法选择其他年份/月份。
您可以更改逻辑(utc.setTimeInMillis(today)
)以使用另一个月。