在我的应用程序中我正在尝试DatePicker设置日期。我想设置日期选择器最大日期是根据系统日期的今天日期。我不知道如何将日期选择器最大日期设置为今天date.May我知道实现目标的正确方法是什么?也许这个问题太基础了,但我找不到合适的解决方案。请帮帮我
这是我的代码:
public class UserDob extends Activity {
TextView tvDisplayDate;
DatePicker datePickerBirthday;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_dob);
ActionBar ab = getActionBar();
ab.setDisplayUseLogoEnabled(false);
ab.setDisplayShowHomeEnabled(true);
ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ab.setCustomView(R.layout.actionbar);
ab.setDisplayHomeAsUpEnabled(true);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#FFFFFF"));
ab.setBackgroundDrawable(colorDrawable);
datePickerBirthday=(DatePicker)findViewById(R.id.dpResult);
tvDisplayDate = (TextView)findViewById(R.id.textViewUserDate);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= 11) {
datePickerBirthday.setCalendarViewShown(false);
}
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String dateStr = sdfDateTime.format(new Date(System.currentTimeMillis()));
String[] dateSplit = dateStr.split("-");
int currentYear = Integer.parseInt(dateSplit[0]);
int currentMonth = Integer.parseInt(dateSplit[1]);
int currentDay = Integer.parseInt(dateSplit[2]);
// to show date and day of week in the TextView
setHumanReadableDate(currentYear, currentMonth, currentDay);
// initialize date picker listener
// currentMonth - 1, because on the picker, 0 is January
datePickerBirthday.init(currentYear, currentMonth - 1, currentDay, birthdayListener);
}
// the date picker listener
OnDateChangedListener birthdayListener = new OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker birthDayDatePicker,
int newYear, int newMonth, int newDay) {
try{
// currentMonth + 1, to retrieve proper month
setHumanReadableDate(newYear, newMonth + 1, newDay);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// show the user a better date format
public void setHumanReadableDate(int newYear, int newMonth, int newDay){
try {
String clickedDate = newYear + "-" + newMonth + "-" + newDay;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = null;
try {
d = sdf.parse(clickedDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat sdfDateTime = new SimpleDateFormat("MMMM dd, yyyy 'is' EEEE", Locale.US);
String dateStr = sdfDateTime.format(d);
tvDisplayDate.setText(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
以上API 11 对于最小日期,您可以使用
android:minDate="mm/dd/yyyy"
or setMinDate(long time)
最长日期
android:maxDate="mm/dd/yyyy" // In XML
setMaxDate(new Date().getTime());// Current time
答案 1 :(得分:0)
如果您使用的API级别高于11,则使用setMaxDate
的{{1}}来设置mex日期。否则创建一个自定义DatePicker并覆盖DatePicker
方法,并在此处应用您的验证
onDateSet