In our daily development process, we may encounter a requirement for choosing the validity period of a credit card, which means we need to select the year and month. However, the system control datepicker supports year, month, and day options by default, such:
So, how can we make the date selector not display? Let's take a look at the source code of datepicker:
In the datepicker source code, you have a private member numberpicker variable mdayspinner, which should be the control used for date selection. The access permission for private is of course difficult because we have a powerful "reflection" function. Let's look at the instance code below;
Mainactivity. Java file:
Public classmainactivity extends activity {privatebutton button; @ override protectedvoid oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); button = (button) findviewbyid (R. id. button); button. setonclicklistener (newonclicklistener () {@ override publicvoid onclick (view v) {datepickerdatepicker = new datepicker (mainactivity. this); datepicker. setcalendarviewshown (false); // uses the reflection mechanism to access the private mdayspinner member and hide it. Try {field dayspinner = datepicker. getclass (). getdeclaredfield ("mdayspinner"); dayspinner. setaccessible (true); (View) dayspinner. get (datepicker )). setvisibility (view. gone);} catch (nosuchfieldexception e) {e. printstacktrace ();} catch (illegalargumentexception e) {e. printstacktrace ();} catch (illegalaccessexception e) {e. printstacktrace ();} calendarmincalendar = calendar. getinstance (); mincalendar. set (calendar. hour_of_day, 0); mincalendar. set (calendar. minute, 0); mincalendar. set (calendar. second, 0); datepicker. setmindate (mincalendar. gettimeinmillis (); calendarmaxcalendar = calendar. getinstance (); maxcalendar. add (calendar. year, 1); datepicker. setmaxdate (maxcalendar. gettimeinmillis (); calendarcurcalendar = calendar. getinstance (); datepicker. init (curcalendar. get (calendar. year), curcalendar. get (calendar. month), curcalendar. get (calendar. day_of_month), null); alertdialog. builderbuilder = new alertdialog. builder (mainactivity. this); builder. setview (datepicker); builder. settitle ("select validity period"); builder. setpositivebutton ("OK", null); alertdialogdialog = builder. create (); dialog. setcanceledontouchoutside (true); dialog. show ();}});}}
Okay. Run the command to see the effect:
Accumulated over time: how to hide datepicker's date Selection