10

How to hide/remove date field in datepickerdialog. Actually my requirement is to use the native date picker dialog but it shows up with day, month, and year. But as per my requirement i need only month and year. So i want to hide or remove the day field from the view.

Any help will be much usefull.

Ishu
  • 5,357
  • 4
  • 16
  • 17

8 Answers8

13

I don't recommend using Reflection to do this kind of thing.

There is a simpler and more pretty way to do so:

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

Be aware that .getDatePicker() method from DatePickerDialog works on API LEVEL >= 11.

6
Private DatePickerDialog createDialogWithoutDateField(){

    DatePickerDialog dpd = new DatePickerDialog(_activity, ExpiryDateSetListener,cyear,cmonth, cday);
    try{
    Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
    for (Field datePickerDialogField : datePickerDialogFields) { 
        if (datePickerDialogField.getName().equals("mDatePicker")) {
            datePickerDialogField.setAccessible(true);
            DatePicker datePicker = (DatePicker) datePickerDialogField.get(dpd);
            Field datePickerFields[] = datePickerDialogField.getType().getDeclaredFields();
            for (Field datePickerField : datePickerFields) {
               if ("mDayPicker".equals(datePickerField.getName())) {
                  datePickerField.setAccessible(true);
                  Object dayPicker = new Object();
                  dayPicker = datePickerField.get(datePicker);
                  ((View) dayPicker).setVisibility(View.GONE);
               }
            }
         }

      }
    }catch(Exception ex){
    }
  return dpd;

}

Use the above code for hiding the day field in DatePickerDialog.

Refer this LINK

Shankar Agarwal
  • 34,573
  • 7
  • 66
  • 64
  • 13
    This is a vile recommendation. The most reliable answer is to roll your own. Even if you want to play script-kiddie games like what is proposed here, don't use reflection -- get at the particular widgets via `getDatePicker()` and `findViewById()` and set their visibility that way. Both approaches make assumptions about internal implementations that may not be valid across Android OS releases or OEM firmware modifications, but at least the `findViewById()` approach will make fewer assumptions (and probably run faster). – CommonsWare May 20 '12 at 13:37
  • mDatePicker.getDatePicker().setCalendarViewShown(false); – Tancho Jul 10 '13 at 15:00
  • 1
    Awesome. But "mDayPicker" does not work. It should be "mDaySpinner". – Karthik Andhamil Oct 08 '13 at 23:52
6

The source code to DatePicker and DatePickerDialog are available for you to clone, refactor into your own package, and modify to suit.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
1
    private Calendar mCalendar;
    mCalendar = Calendar.getInstance();// Initialize Calendar

dialog_date_picker.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/rounded_corners"
android:orientation="vertical"
android:padding="8dp">
<DatePicker
    android:id="@+id/date_picker"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="4"
    android:calendarViewShown="false"
    android:datePickerMode="spinner" />
<Button
    android:id="@+id/date_time_set"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="@color/colorPrimary"
    android:text="Set"
    android:textColor="@color/colorWhite" /></LinearLayout>

DialogMethod called on Click:

private void ExpiryDialog() {
    System.out.println("Inside Dialog Box");
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_date_picker);
    dialog.show();
    final DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.date_picker);
    date_time_set = (Button) dialog.findViewById(R.id.date_time_set);
    datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), null);

    LinearLayout ll = (LinearLayout) datePicker.getChildAt(0);
    LinearLayout ll2 = (LinearLayout) ll.getChildAt(0);
    ll2.getChildAt(1).setVisibility(View.INVISIBLE);

    date_time_set.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view){
            dialog.dismiss();
            Integer month = datePicker.getMonth()+1;
            Integer year = datePicker.getYear();
            expMonth = (month.toString().length()   == 1 ? "0"+month.toString():month.toString());
            expYear = year.toString();
            etExpiryDate.setText(expMonth + "/" + expYear);
        }
    });
}

This code works and hides the day in a DatePicker, so I can show Expiry Date for Cards. Enjoy!!

SH7890
  • 545
  • 2
  • 7
  • 20
ULHAS PATIL
  • 862
  • 8
  • 19
1
((ViewGroup) datePickerDialog.getDatePicker()).findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).setVisibility(View.GONE); 

This works properly

eli-k
  • 10,898
  • 11
  • 40
  • 44
0
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_DARK,
new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        txtMonth.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
    }

}, mYear, mMonth, mDay);
((ViewGroup) datePickerDialog.getDatePicker()).findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).setVisibility(View.GONE);
datePickerDialog.show();

refer this link Disable day selection on datepicker example

Max Base
  • 639
  • 1
  • 7
  • 15
Thinesh
  • 555
  • 1
  • 6
  • 7
0

I am a little too late but posting the edited answer provided by @ULHAS PATIL above that works in case someone needs the same thing!

private Calendar mCalendar;
mCalendar = Calendar.getInstance();// Initialize Calendar

The xml layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/DarkGrey"
    android:orientation="vertical"
    android:padding="8dp">
    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4"
        android:calendarViewShown="false"
        android:theme="@style/DialogTheme"
        android:datePickerMode="spinner" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_gravity="end"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="25dp"
            android:layout_centerVertical="true"
            android:layout_gravity="start"
            android:layout_marginVertical="20dp"
            android:layout_marginStart="50dp"
            android:background="@android:color/transparent"
            android:gravity="center"
            android:text="@string/cancel"
            android:textAllCaps="false"
            android:textColor="@color/grey"
            android:textSize="20sp" />

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/ok"
            android:layout_width="48dp"
            android:layout_height="25dp"
            android:layout_centerVertical="true"
            android:layout_gravity="end"
            android:layout_marginVertical="20dp"
            android:layout_marginStart="0dp"
            android:layout_marginEnd="10dp"
            android:layout_toEndOf="@id/cancel"
            android:background="@android:color/transparent"
            android:fontFamily="@font/kontora_extra_bold"
            android:gravity="center"
            android:text="@string/ok"
            android:textAllCaps="false"
            android:textColor="@color/CoralRed"
            android:textSize="20sp" />
    </RelativeLayout>
</LinearLayout>

There should be index 0 to hide the date filled, in ll2.getChildAt(0).setVisibility(View.GONE); and visibility set to View.GONE so the space for the date field is not occupied.

private void createDialogWithoutDateField() {
    Calendar mCalendar;
    mCalendar = Calendar.getInstance();
    System.out.println("Inside Dialog Box");
    final Dialog dialog = new Dialog(requireContext());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.date_picker_layout);
    dialog.show();

    final DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.date_picker);
    AppCompatButton okBtn = (AppCompatButton) dialog.findViewById(R.id.ok);
    AppCompatButton cancelBtn = (AppCompatButton) dialog.findViewById(R.id.cancel);
    datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), null);

    LinearLayout ll = (LinearLayout) datePicker.getChildAt(0);
    LinearLayout ll2 = (LinearLayout) ll.getChildAt(0);
    ll2.getChildAt(0).setVisibility(View.GONE);
    okBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
            Integer month = datePicker.getMonth() + 1;
            Integer year = datePicker.getYear();
            String expYear = year.toString();
            tvMonthYear.setText(month+ " " + expYear);
        }
    });
 cancelBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });
}
JB08
  • 41
  • 3
-4

I don't think you need to go that deep unless you wanna customize it.. there is the :

mDatePicker.getDatePicker().setCalendarViewShown(false);

which is a very legitimate call to remove the calendar segment.

Tancho
  • 1,581
  • 3
  • 22
  • 40