我有一个非常简单的日期选择器片段:
public class DatePickerFragment extends DialogFragment implements
OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Activity a = getActivity();
Button dateDueButton = (Button) a.findViewById(R.id.dateDue);
String sYear = Integer.toString(year).substring(2, 4);
String sMonth = Integer.toString(month + 1);
String sDay = Integer.toString(day);
dateDueButton.setText(sMonth + "/" + sDay + "/" + sYear);
}
}
我希望能够设置“日期边界”。例如,如果当天是2月9日,我希望仅在2月10日或更晚的日期显示在片段上。我该如何实施呢?
答案 0 :(得分:2)
使用此方法 getDatePicker()
,您将从DatepickerDialog获取Datepicker对象public class DatePickerFragment extends DialogFragment implements
OnDateSetListener {
private DatePickerDialog datepic;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
datepic=new DatePickerDialog(getActivity(), this, year, month, day);
return datepic;
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Activity a = getActivity();
Button dateDueButton = (Button) a.findViewById(R.id.dateDue);
String sYear = Integer.toString(year).substring(2, 4);
String sMonth = Integer.toString(month + 1);
String sDay = Integer.toString(day);
dateDueButton.setText(sMonth + "/" + sDay + "/" + sYear);
}
public void setMinimumDate(Calendar mintime){
datepic.getDatePicker().setMinDate(mintime.getTimeInMillis());
}
public void setMaximumDate(Calendar maxtime){
datepic.getDatePicker().setMaxDate(maxtime.getTimeInMillis());
}
使用公共方法setMinimumDate和setMaximumDate来设置边界
答案 1 :(得分:1)
使用minDate
课程中的maxDate
和DatePicker
参数。
请注意,这些是API级别11类,因此您必须自己实现此功能以实现向后兼容性。
答案 2 :(得分:0)
那么,您可以获取当前系统日期并将其与用户选择的日期进行比较。如果用户选择的日期小于当前日期,则可以在日期上设置边界。否则,您可以继续保存。给代码片段可以帮助您,
public static long getTimeDiffInDays(String birthday) {
int beforeLenght = birthday.length();
int afterLenght = birthday.replace("/", "").length();
int checkFormat = beforeLenght - afterLenght;
String newBirthday;
if (checkFormat == 2) {
int lastIndex = birthday.lastIndexOf("/");
newBirthday = birthday.substring(0, lastIndex).trim();
} else {
newBirthday = birthday.trim();
}
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
Calendar now = Calendar.getInstance();
Date newDate = new Date();
Date olddate = new Date();
try {
newDate = sdf.parse(sdf.format(now.getTime()));
olddate = sdf.parse(newBirthday);
} catch (ParseException e) {
e.printStackTrace();
}
long datediff = (olddate.getTime() - newDate.getTime())
/ (1000 * 60 * 60 * 24);
if (datediff < 0)
return datediff + 365;
else
return datediff;
}