[Android]只显示月和日的DatePickerDialog
正文 一、效果图 1.1 默认 1.2 处理后 二、实现代码 2.1 代码片段1 /** *从当前Dialog中查找DatePicker子控件 * *@paramgroup *@return */ privateDatePickerfindDatePicker(ViewGroupgroup){ if(group!=null){ for(inti=0,j=group.getChildCount();i<j;i++){ Viewchild=group.getChildAt(i); if(childinstanceofDatePicker){ return(DatePicker)child; }elseif(childinstanceofViewGroup){ DatePickerresult=findDatePicker((ViewGroup)child); if(result!=null) returnresult; } } } returnnull; } 代码说明: 通过断点也看到Dialog的ContentView里有DatePicker子控件,这里通过遍历的办法来查找这个控件。 2.2 使用代码 finalCalendarcal=Calendar.getInstance(); mDialog=newCustomerDatePickerDialog(getContext(),this, cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); mDialog.show(); DatePickerdp=findDatePicker((ViewGroup)mDialog.getWindow().getDecorView()); if(dp!=null){ ((ViewGroup)dp.getChildAt(0)).getChildAt(0).setVisibility(View.GONE); } 代码说明: 通过源码可以看得到DatePicker内置三个NumberPicker控件,依次表示年、月、日,隐藏掉第一个即可。 三、补充 后续使用中发现标题栏也要改,通过查看DatePickerDialog源码,需要自定义并实现onDateChanged方法才可实现,如下代码: classCustomerDatePickerDialogextendsDatePickerDialog{ publicCustomerDatePickerDialog(Contextcontext, OnDateSetListenercallBack,intyear,intmonthOfYear, intdayOfMonth){ super(context,callBack,year,monthOfYear,dayOfMonth); } @Override publicvoidonDateChanged(DatePickerview,intyear,intmonth,intday){ super.onDateChanged(view,year,month,day); mDialog.setTitle((month+1)+"月"+day+"日"); } } 本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/669257,如需转载请自行联系原作者