Android 自定义DatePicker / DatePickerDialog

问:如何让DatePicker / DatePickerDialog只显示年?

答:DatePickerDialog里面也是一个DatePicker,可以这样获取到。

DatePicker dp = findDatePicker((ViewGroup)dpDialog.getWindow().getDecorView());

	private DatePicker findDatePicker(ViewGroup group) {
		if (group != null) {
			for (int i = 0, j = group.getChildCount(); i < j; i++) {
				View child = group.getChildAt(i);
				if (child instanceof DatePicker) {
					return (DatePicker) child;
				} else if (child instanceof ViewGroup) {
					DatePicker result = findDatePicker((ViewGroup) child);
					if (result != null)
						return result;
				}
			}
		}
		return null;
	}

因此,问题就是让DatePicker显示年了。

//android XXX以下版本
this.findAndHideField(dp, "mDayPicker");
this.findAndHideField(dp, "mMonthPicker");
//android XXX以上版本
this.findAndHideField(dp, "mDaySpinner");
this.findAndHideField(dp, "mMonthSpinner");
//为了兼容,建议都写上。
 
  
	private void findAndHideField(DatePicker datepicker, String name) {
		try {
			Field field = DatePicker.class.getDeclaredField(name);
			field.setAccessible(true);
			View fieldInstance = (View) field.get(datepicker);
			fieldInstance.setVisibility(View.GONE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


在高版本的系统上,会出现一个Calendar,可以采用下面方式隐藏

//Hide calendar if it exists
ViewGroup group = (ViewGroup)this.datePicker.getChildAt(0);
// 0:datepicker , 1:calendar
group = (ViewGroup) group.getChildAt(1);group.setVisibility(View.GONE);

原理就是查看DatePicker由那些view组成,隐藏不需要的view即可。同理,可用下面方式隐藏月、日

//Hide calendar if it exists
ViewGroup group = (ViewGroup)this.datePicker.getChildAt(0);

// 0:datepicker , 1:calendar
group = (ViewGroup) group.getChildAt(0);

// 0 for year, 1 for month, 2 for day
group.getChildAt(1).setVisibility(View.GONE);
group.getChildAt(2).setVisibility(View.GONE);


另外,已经有高人仿IOS上的样式了,参考:http://code.google.com/p/android-wheel/    The wheel widget for Android.

里面有自定义的Date Picker,样式是这个样子滴

Android 自定义DatePicker / DatePickerDialog_第1张图片


你可能感兴趣的:(Android开发)