zoukankan      html  css  js  c++  java
  • [Android]只显示月和日的DatePickerDialog

    前言

     需求要只显示月和日的日历控件,又不想自定义控件,最简单的办法就是隐藏显示年的这个框了,但DatePickerDialog并没有直接提供方法来操作,这里分享一个笨办法:)

    声明

      欢迎转载,但请保留文章原始出处:) 

        博客园:http://www.cnblogs.com

        农民伯伯: http://over140.cnblogs.com   

    正文

      一、效果图

        1.1 默认

     

        1.2 处理后 

     

      二、实现代码

        2.1  代码片段1

        /**
         * 从当前Dialog中查找DatePicker子控件
         * 
         * 
    @param group
         * 
    @return
         
    */
        
    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;

        } 

          代码说明:
            通过断点也看到Dialog的ContentView里有DatePicker子控件,这里通过遍历的办法来查找这个控件。

        2.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) dp.getChildAt(
    0)).getChildAt(0).setVisibility(View.GONE);

            } 

          代码说明:

            通过源码可以看得到DatePicker内置三个NumberPicker控件,依次表示年、月、日,隐藏掉第一个即可。

        三、补充

          后续使用中发现标题栏也要改,通过查看DatePickerDialog源码,需要自定义并实现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((month 
    + 1+ "" + day + "");
            }
        }
  • 相关阅读:
    Bootstrap下拉菜单的使用(附源码文件)--Bootstrap
    滚动条实现RGB颜色的调制(窗体程序)--JAVA基础
    登录对话框(窗体程序)--JAVA基础
    Bootstrap表格样式(附源码文件)--Bootstrap
    Block 循环引用(中)
    Block 循环引用(上)
    依赖注入
    类型转化
    Block 实践
    动态创建 Plist 文件
  • 原文地址:https://www.cnblogs.com/over140/p/2181532.html
Copyright © 2011-2022 走看看