Android DatePickerDialog 只显示年月

Android DatePickerDialog 只显示年月

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

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

实现的代码:

    1. 通过遍历方法查找DatePicker里的子控件:年、月、日
[java]  view plain copy print ?
  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 plain copy print ?
  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 plain copy print ?
  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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值