Android DatePicker cambia a solo mes y año

Tengo un DatePickerDialog y quiero ver solo Mes y Año. ¿Cómo puedo cambiar este código?

public void chooseDate2(View v) { new DatePickerDialog( act.this, d1, dateAndTime1.get(Calendar.YEAR) + 2, dateAndTime1.get(Calendar.MONTH), dateAndTime1.get(Calendar.DAY_OF_MONTH) ).show(); } private void updateLabel2() { scadenza.setText(fmtDateAndTime.format(dateAndTime1.getTime())); } DatePickerDialog.OnDateSetListener d1=new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { dateAndTime1.set(Calendar.YEAR, year); dateAndTime1.set(Calendar.MONTH, monthOfYear); dateAndTime1.set(Calendar.DAY_OF_MONTH, dayOfMonth); updateLabel2(); } }; 

Gracias

Pruebe el siguiente código. DatePicker un DatePicker con solo el año y el mes (sin día)

 private DatePickerDialog createDialogWithoutDateField() { DatePickerDialog dpd = new DatePickerDialog(this, null, 2014, 1, 24); try { java.lang.reflect.Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields(); for (java.lang.reflect.Field datePickerDialogField : datePickerDialogFields) { if (datePickerDialogField.getName().equals("mDatePicker")) { datePickerDialogField.setAccessible(true); DatePicker datePicker = (DatePicker) datePickerDialogField.get(dpd); java.lang.reflect.Field[] datePickerFields = datePickerDialogField.getType().getDeclaredFields(); for (java.lang.reflect.Field datePickerField : datePickerFields) { Log.i("test", datePickerField.getName()); if ("mDaySpinner".equals(datePickerField.getName())) { datePickerField.setAccessible(true); Object dayPicker = datePickerField.get(datePicker); ((View) dayPicker).setVisibility(View.GONE); } } } } } catch (Exception ex) { } return dpd; } 

Este método devuelve un diálogo de selector de fecha. Por lo tanto, en el método onClick su botón agregue el siguiente código para mostrar su diálogo.

 createDialogWithoutDateField().show(); 

Como recientemente descubrí este problema, probé varias soluciones de esta publicación y preguntas similares sobre Stackoverflow.

Desafortunadamente no encontré ninguna solución funcional especialmente para Android 5+

Terminé implementando mi propio DialogFragment simple incorporando dos NumberPickers. Esto debería ser compatible con todas las versiones de 3.0 y superiores.

Aquí está el código:

  public class MonthYearPickerDialog extends DialogFragment { private static final int MAX_YEAR = 2099; private DatePickerDialog.OnDateSetListener listener; public void setListener(DatePickerDialog.OnDateSetListener listener) { this.listener = listener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); Calendar cal = Calendar.getInstance(); View dialog = inflater.inflate(R.layout.date_picker_dialog, null); final NumberPicker monthPicker = (NumberPicker) dialog.findViewById(R.id.picker_month); final NumberPicker yearPicker = (NumberPicker) dialog.findViewById(R.id.picker_year); monthPicker.setMinValue(1); monthPicker.setMaxValue(12); monthPicker.setValue(cal.get(Calendar.MONTH) + 1); int year = cal.get(Calendar.YEAR); yearPicker.setMinValue(year); yearPicker.setMaxValue(MAX_YEAR); yearPicker.setValue(year); builder.setView(dialog) // Add action buttons .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { listener.onDateSet(null, yearPicker.getValue(), monthPicker.getValue(), 0); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MonthYearPickerDialog.this.getDialog().cancel(); } }); return builder.create(); } } 

Y el diseño

         

Para mostrar el uso del diseño:

 MonthYearPickerDialog pd = new MonthYearPickerDialog(); pd.setListener(this); pd.show(getFragmentManager(), "MonthYearPickerDialog"); 

No recomiendo usar Reflection para hacer este tipo de cosas.

Hay una manera más simple y más bonita de hacerlo:

 ((ViewGroup) datePickerDialog.getDatePicker()).findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).setVisibility(View.GONE); 

Tenga en cuenta que el método .getDatePicker() de DatePickerDialog funciona en API LEVEL >= 11 .

Además, no funciona en API LEVEL> = 21.

Más forma de avance de Stephan Klein Respuesta.

Como tengo un requisito para hacer el año opcional . Y también he manejado la fecha como el 28 de febrero y también manejo el año bisiesto .

MonthYearPickerDialog

 public class MonthYearPickerDialog extends DialogFragment { private DatePickerDialog.OnDateSetListener listener; private int daysOfMonth = 31; private NumberPicker monthPicker; private NumberPicker yearPicker; private NumberPicker dayPicker; private Calendar cal = Calendar.getInstance(); public static final String MONTH_KEY = "monthValue"; public static final String DAY_KEY = "dayValue"; public static final String YEAR_KEY = "yearValue"; int monthVal = -1 , dayVal = -1 , yearVal =-1 ; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getArguments(); if(extras != null){ monthVal = extras.getInt(MONTH_KEY , -1); dayVal = extras.getInt(DAY_KEY , -1); yearVal = extras.getInt(YEAR_KEY , -1); } } public static MonthYearPickerDialog newInstance(int monthIndex , int daysIndex , int yearIndex) { MonthYearPickerDialog f = new MonthYearPickerDialog(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt(MONTH_KEY, monthIndex); args.putInt(DAY_KEY, daysIndex); args.putInt(YEAR_KEY, yearIndex); f.setArguments(args); return f; } public void setListener(DatePickerDialog.OnDateSetListener listener) { this.listener = listener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { //getDialog().setTitle("Add Birthday"); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); View dialog = inflater.inflate(R.layout.month_year_picker, null); monthPicker = (NumberPicker) dialog.findViewById(R.id.picker_month); yearPicker = (NumberPicker) dialog.findViewById(R.id.picker_year); dayPicker = (NumberPicker) dialog.findViewById(R.id.picker_day); monthPicker.setMinValue(1); monthPicker.setMaxValue(12); if(monthVal != -1)// && (monthVal > 0 && monthVal < 13)) monthPicker.setValue(monthVal); else monthPicker.setValue(cal.get(Calendar.MONTH) + 1); monthPicker.setDisplayedValues(new String[]{"Jan","Feb","Mar","Apr","May","June","July", "Aug","Sep","Oct","Nov","Dec"}); dayPicker.setMinValue(1); dayPicker.setMaxValue(daysOfMonth); if(dayVal != -1) dayPicker.setValue(dayVal); else dayPicker.setValue(cal.get(Calendar.DAY_OF_MONTH)); monthPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { switch (newVal){ case 1:case 3:case 5: case 7:case 8:case 10: case 12: daysOfMonth = 31; dayPicker.setMaxValue(daysOfMonth); break; case 2: daysOfMonth = 28; dayPicker.setMaxValue(daysOfMonth); break; case 4:case 6: case 9:case 11: daysOfMonth = 30; dayPicker.setMaxValue(daysOfMonth); break; } } }); int maxYear = cal.get(Calendar.YEAR);//2016 final int minYear = 1916;//1997; int arraySize = maxYear - minYear; String[] tempArray = new String[arraySize]; tempArray[0] = "---"; int tempYear = minYear+1; for(int i=0 ; i < arraySize; i++){ if(i != 0){ tempArray[i] = " " + tempYear + ""; } tempYear++; } Log.i("", "onCreateDialog: " + tempArray.length); yearPicker.setMinValue(minYear+1); yearPicker.setMaxValue(maxYear); yearPicker.setDisplayedValues(tempArray); if(yearVal != -1) yearPicker.setValue(yearVal); else yearPicker.setValue(tempYear -1); yearPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { try { if(isLeapYear(picker.getValue())){ daysOfMonth = 29; dayPicker.setMaxValue(daysOfMonth); } }catch (Exception e){ e.printStackTrace(); } } }); builder.setView(dialog) // Add action buttons .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { int year = yearPicker.getValue(); if(year == (minYear+1)){ year = 1904; } listener.onDateSet(null, year, monthPicker.getValue(), dayPicker.getValue()); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MonthYearPickerDialog.this.getDialog().cancel(); } }); return builder.create(); } public static boolean isLeapYear(int year) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365; } } 

Y lo llamo así

 Calendar calendar = Calendar.getInstance(); if(etBirthday.getText().length()> 0 ){ if(checkIsYearAvailable(etBirthday.getText().toString().trim())) calendar = DateTimeOp.getCalendarFromFormat(etBirthday.getText().toString().trim(), Constants.dateFormat21); else calendar = DateTimeOp.getCalendarFromFormat(etBirthday.getText().toString().trim() + ", 1917",Constants.dateFormat21); } MonthYearPickerDialog pd = MonthYearPickerDialog.newInstance(calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.YEAR)); pd.setListener(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { String formatedDate = ""; if(selectedYear == 1904) { String currentDateFormat = selectedMonth + "/" + selectedDay;// + "/" + selectedYear; //"MM/dd/yyyy" formatedDate = DateTimeOp.oneFormatToAnother(currentDateFormat, Constants.dateFormat20, Constants.dateFormat24); } else{ String currentDateFormat = selectedMonth + "/" + selectedDay + "/" + selectedYear; //"MM/dd/yyyy" formatedDate = DateTimeOp.oneFormatToAnother(currentDateFormat, Constants.dateFormat0, Constants.dateFormat21); } etBirthday.setText(formatedDate); } }); pd.show(getFragmentManager(), "MonthYearPickerDialog"); 

month_year_picker.xml

         

funciona bien API <21.

 public class MonPickerDialog extends DatePickerDialog { public MonPickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { super(context, callBack, year, monthOfYear, dayOfMonth); this.setTitle(year + " / " + (monthOfYear + 1)); int field = TFKBApp.getInstance().getApplicationLanguage().equals(getContext().getString(R.string.turkish_tr)) ? 0 : 1; // it change depend on language date type. ((ViewGroup) ((ViewGroup) this.getDatePicker().getChildAt(0)).getChildAt(0)).getChildAt(field).setVisibility(View.GONE); } @Override public void onDateChanged(DatePicker view, int year, int month, int day) { super.onDateChanged(view, year, month, day); this.setTitle(year + " / " + (month + 1)); } } 

el calendario llamado en clase.

 public void showMonPicker() { final Calendar localCalendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM"); try { Date date = sdf.parse("2013/08"); localCalendar.setTime(date); } catch (Exception e) { } new MonPickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { localCalendar.set(Calendar.YEAR, year); localCalendar.set(Calendar.MONTH, monthOfYear); fragTaxOthersInfoTaxDate.setText(year + "/" + monthOfYear); } }, localCalendar.get(Calendar.YEAR), localCalendar.get(Calendar.MONTH), localCalendar.get(Calendar.DATE)).show(); } 

Esto funciona para mí bien:

 DatePickerDialog monthDatePickerDialog = new DatePickerDialog(activity, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { monthTextView.setText(year + "/" + (month + 1)); } }, yearNow, monthNow, dayNow){ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getDatePicker().findViewById(getResources().getIdentifier("day","id","android")).setVisibility(View.GONE); } }; monthDatePickerDialog.setTitle("select_month"); monthDatePickerDialog.show(); 

Esta es una vieja pregunta, pero ahora puedes usar “BetterPickers”:

https://github.com/code-troopers/android-betterpickers

Y use ExpirationPicker.

Espero que esto lo resuelva para otras almas perdidas que buscaron en Google por todas partes.