今天写一个日期控件,默认显示年月日,但是我现在只想显示年月,在网上找了一个比较简单容易了理解的方法,分享如下:
先看一个效果图:
处理前:
处理后:
实现的代码:
1. 通过遍历方法查找DatePicker里的子控件:年、月、日
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;
}
2.隐藏不想显示的子控件,这里隐藏日控件
final Calendar cal = Calendar.getInstance();
mDialog = new CustomerDatePickerDialog(getContext(), this,
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH));
mDialog.show();
DatePicker dp = findDatePicker((ViewGroup) mDialog.getWindow().getDecorView());
if (dp != null) {
((ViewGroup)((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
}
如果想隐藏年,把 getChildAt(2)改为getChildAt(0)...
3.补充:如果标题栏也想改,需要自定义并实现onDateChanged方法才可实现,代码:
class CustomerDatePickerDialog extends DatePickerDialog {
public CustomerDatePickerDialog(Context context,
OnDateSetListener callBack, int year, int monthOfYear,
int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
}
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
super.onDateChanged(view, year, month, day);
mDialog.setTitle(year + "年" + (month + 1) + "月");
}
}