如果使用了android:theme="@android:style/Theme.Light.NoTitleBar" 样式的DateickerDialog,那么显示年月日的地方是EditText,是可以编辑的。
但是,在大多数手机上面,该EditText被修改后立即点击确定。那么获取到的年月日还是之前的年月日,我们没能够获取到EditText修改后的实际数据。 我们可以巧妙地通过主动触发焦点的改变,来使得DatePicker的年月日改变,那么这样我们再获取到的DatePicker的年月日,就是修改后的年月日。
如下所示:
manifest.xml
application:
android:theme="@android:style/Theme.Light.NoTitleBar"
activity:
String TAG = getClass().getSimpleName();
DatePickerDialog datePickerDialog;
int year = 1990,month = 0,day = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int realYear = year;
int realMonthOfYear = monthOfYear;
int realDayOfMonth = dayOfMonth;
Calendar cal = Calendar.getInstance();
try{
datePickerDialog.getDatePicker().requestFocus();
Log.d(TAG, "DatePickerDialog " + datePickerDialog.getDatePicker().getCalendarView().getDate());
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(datePickerDialog.getDatePicker().getCalendarView().getDate()));
realYear = calendar.get(Calendar.YEAR);
realMonthOfYear = calendar.get(Calendar.MONTH);
realDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
Log.d(TAG,"year is :"+year+ "\tmonth is :"+month+"\tday is :"+day
+"\nrealYear is => "+realYear+"\trealMonth is =>"+realMonthOfYear+"\trealDayis =>"+realDayOfMonth);
}catch (Exception e){
Log.d(TAG,"DatePickerDialog "+e.toString());
}
}
},year,month,day);
datePickerDialog.show();
}
运行后直接把年的位置输入1994(不要通过点击+-号改变数字),点击确定。
(部分手机没有此问题,因此部分手机会在点击确定的时候把焦点跳到下一个EditText去!)
输出结果如下:
04-04 14:50:24.969 8896-8896 D/MainActivity: DatePickerDialog 757407000477
04-04 14:50:24.970 8896-8896 D/MainActivity: year is :1990 month is :0 day is :1
ealYear is => 1994 realMonth is =>0 realDayis =>1
同理,TimePickerDialog也如此,需要把焦点改变。
但是TimePickerDialog并不能直接获取到TimePicker,那么我们可以通过反射的方式实现。
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view,
int hourOfDay, int minute) {
int realHourOfDay = hourOfDay;
int realMinute = minute;
Log.d(TAG,"======================>");
try {
Field mTimePicker = timePicker.getClass().getDeclaredField("mTimePicker");
mTimePicker.setAccessible(true);
TimePicker timePicker = (TimePicker) (mTimePicker.get(timePicker));
timePicker.requestFocus();
realHourOfDay = timePicker.getCurrentHour();
realMinute = timePicker.getCurrentMinute();
Log.d(TAG, "hourOfDay =>"+hourOfDay+"\t"+"minute =>"+minute+
"\nrealHourOfDay=>" + timePicker.getCurrentHour() + " realMinute=>" + timePicker.getCurrentMinute());
} catch (Exception e) {
Log.e(TAG,e.toString());
}
}
}