Android DatePickerDialog 只显示年月

来源:互联网 发布:网络代售许可证 编辑:程序博客网 时间:2024/06/05 01:53
Android DatePickerDialog 只显示年月

今天写一个日期控件,默认显示年月日,但是我现在只想显示年月,在网上找了一个比较简单容易了理解的方法,分享如下:

先看一个效果图:
处理前:  处理后:

实现的代码:

    1. 通过遍历方法查找DatePicker里的子控件:年、月、日
[java] view plaincopyprint?
  1. private DatePicker findDatePicker(ViewGroup group) {  
  2.         if (group != null) {  
  3.             for (int i = 0, j = group.getChildCount(); i < j; i++) {  
  4.                 View child = group.getChildAt(i);  
  5.                 if (child instanceof DatePicker) {  
  6.                     return (DatePicker) child;  
  7.                 } else if (child instanceof ViewGroup) {  
  8.                     DatePicker result = findDatePicker((ViewGroup) child);  
  9.                     if (result != null)  
  10.                         return result;  
  11.                 }  
  12.             }  
  13.         }  
  14.         return null;  
  15.     }   

  2.隐藏不想显示的子控件,这里隐藏日控件

[java] view plaincopyprint?
  1. final Calendar cal = Calendar.getInstance();  
  2. mDialog = new CustomerDatePickerDialog(getContext(), this,  
  3.     cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),  
  4.     cal.get(Calendar.DAY_OF_MONTH));  
  5. mDialog.show();  
  6.   
  7. DatePicker dp = findDatePicker((ViewGroup) mDialog.getWindow().getDecorView());  
  8. if (dp != null) {  
  9.     ((ViewGroup)((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);  
  10. }   

如果想隐藏年,把getChildAt(2)改为getChildAt(0)...

  3.补充:如果标题栏也想改,需要自定义并实现onDateChanged方法才可实现,代码:

[java] view plaincopyprint?
  1. class CustomerDatePickerDialog extends DatePickerDialog {  
  2.     public CustomerDatePickerDialog(Context context,  
  3.             OnDateSetListener callBack, int year, int monthOfYear,  
  4.             int dayOfMonth) {  
  5.         super(context, callBack, year, monthOfYear, dayOfMonth);  
  6.     }  
  7.   
  8.     @Override  
  9.     public void onDateChanged(DatePicker view, int year, int month, int day) {  
  10.         super.onDateChanged(view, year, month, day);  
  11.         mDialog.setTitle(year + "年" + (month + 1) + "月");  
  12.     }  
  13. }  
0 0