是否可以允许datePicker仅显示日期并隐藏年份和 一个月?
我有两个活动,在活动A中,我有datePicker,它只显示月份和年份。在活动B中,我希望datePicker仅显示日期,但无法从互联网上找到任何解决方案。
活动A的ScreenShot
假设用户选择 2018年6月。然后在活动B 中,datePicker将显示2018年6月作为对话框标题,并且仅允许用户选择日期。
活动B
month = getIntent().getStringExtra("month"); // Jun 2018
date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog(DATE_DIALOG_ID);
}
});
DatePickerDialog.OnDateSetListener mDateSetListner = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
DatePickerDialog datePickerDialog = this.customDatePicker();
return datePickerDialog;
}
return null;
}
private DatePickerDialog customDatePicker() {
DatePickerDialog dpd = new DatePickerDialog(this, mDateSetListner,
mYear, mMonth, mDay);
try {
Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
for (Field datePickerDialogField : datePickerDialogFields) {
if ((datePickerDialogField.getName().equals("mYearPicker"))||(datePickerDialogField.getName().equals("mMonthPicker"))) {
datePickerDialogField.setAccessible(true);
DatePicker datePicker = (DatePicker) datePickerDialogField
.get(dpd);
Field datePickerFields[] = datePickerDialogField.getType()
.getDeclaredFields();
for (Field datePickerField : datePickerFields) {
if ("mDayPicker".equals(datePickerField.getName())
|| "mDaySpinner".equals(datePickerField
.getName())) {
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}
}
}
}
} catch (Exception ex) {
}
return dpd;
}
答案 0 :(得分:2)
尝试以下代码
DatePickerDialog dpd = new DatePickerDialog(getActivity(), this, year, month, day);
try {
Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
for (Field datePickerDialogField : datePickerDialogFields) {
if (datePickerDialogField.getName().equals("mDatePicker")) {
datePickerDialogField.setAccessible(true);
DatePicker datePicker = (DatePicker) datePickerDialogField
.get(dpd);
Field datePickerFields[] = datePickerDialogField.getType()
.getDeclaredFields();
for (Field datePickerField : datePickerFields) {
if ("mYearPicker".equals(datePickerField.getName())
|| "mYearSpinner".equals(datePickerField
.getName()||"mMonthPicker".equals(datePickerField.getName())||"mMonthSpinner".equals(datePickerField.getName())) {
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}