2

I want date picker in which i can select year, month and date. like this,

enter image description here

But i get date picker like this,

enter image description here

I want to select year and month but in above date picker i can select only month This is my code :

DatePickerDialog.OnDateSetListener mDateListener;

edBirthday.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog =  new DatePickerDialog(
                        RegisterActivity.this,
                        android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                        mDateListener,
                        year,month,day
                );
                dialog.getWindow().setBackgroundDrawable( new ColorDrawable( Color.TRANSPARENT ) );
                dialog.show();
            }
        } );

        mDateListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker ,int year ,int month ,int day) {
                month = month + 1;

                Log.d( "onDateSet" , month + "/" + day + "/" + year );
                edBirthday.setText( new StringBuilder().append( day ).append( "-" )
                        .append( month ).append( "-" ).append( year ) );
            }
        };
Jakir Hossain
  • 3,830
  • 1
  • 15
  • 29
Unnati Patadia
  • 662
  • 3
  • 19
  • 39

5 Answers5

3

Yes this is possible using custom dialog,

Create lay_calander.xml

<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/datePicker"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:calendarViewShown="false"
    android:datePickerMode="spinner" />

Create Java Class for Your Custom Dialog,

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;

import java.util.Calendar;

public class MyDatePickerDialog extends AlertDialog implements DialogInterface.OnClickListener, DatePicker.OnDateChangedListener {

    private DatePickerDialog.OnDateSetListener mDateSetListener;
    private DatePicker mDatePicker;

    protected MyDatePickerDialog(@NonNull Context context) {
        super(context);
        init();
    }

    protected MyDatePickerDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        init();
    }

    protected MyDatePickerDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        init();
    }


    private void init() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.lay_calander, null);
        mDatePicker = view.findViewById(R.id.datePicker);
        setView(view);
    }

    public void showDatePicker(DatePickerDialog.OnDateSetListener listener, Calendar defaultDate) {

        setButton(BUTTON_POSITIVE, getContext().getString(android.R.string.ok), this);
        setButton(BUTTON_NEGATIVE, getContext().getString(android.R.string.cancel), this);

        mDateSetListener = listener;

        if (defaultDate == null) {
            defaultDate = Calendar.getInstance();

        }
        int year = defaultDate.get(Calendar.YEAR);
        int monthOfYear = defaultDate.get(Calendar.MONTH);
        int dayOfMonth = defaultDate.get(Calendar.DAY_OF_MONTH);
        mDatePicker.init(year, monthOfYear, dayOfMonth, this);

        show();

    }


    @Override
    public void onClick(@NonNull DialogInterface dialog, int which) {
        switch (which) {
            case BUTTON_POSITIVE:
                if (mDateSetListener != null) {
                    // Clearing focus forces the dialog to commit any pending
                    // changes, e.g. typed text in a NumberPicker.
                    mDatePicker.clearFocus();
                    if (mDateSetListener != null) {
                        mDateSetListener.onDateSet(mDatePicker, mDatePicker.getYear(),
                                mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
                    }
                }
                break;
            case BUTTON_NEGATIVE:
                cancel();
                break;
        }
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        mDatePicker.init(year, monthOfYear, dayOfMonth, this);
    }
}

Call Dialog from your activity,

MyDatePickerDialog dialog = new MyDatePickerDialog(this);
        dialog.setTitle("Set Date");
        dialog.showDatePicker(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                //Date select callback
            }
        }, Calendar.getInstance());

Your Output looks like, enter image description here

Make sure your AppTheme Shoud be Extend AppCompat, Manifest - android:theme="@style/AppTheme"

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
Kintan Patel
  • 1,230
  • 8
  • 15
0

Let's try this code:

MainActivity.java

package com.antonino.datepicker;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

import java.util.Calendar;

//import android.icu.util.Calendar;

public class MainActivity extends Activity {

    private static TextView Output;
    private Button changeDate;

    private int year;
    private int month;
    private int day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Output = (TextView) findViewById(R.id.Output);
        changeDate = (Button) findViewById(R.id.changeDate);

        // Get current date by calendar

        final Calendar c = Calendar.getInstance();
        year  = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day   = c.get(Calendar.DAY_OF_MONTH);

        // Show current date
        Output.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(month + 1).append("-").append(day).append("-")
                .append(year).append(" "));

        // Button listener to show date picker dialog
        changeDate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // On button click show datepicker dialog
                DialogFragment newFragment = new SelectDateFragment();
                newFragment.show(getFragmentManager(), "DatePicker");

            }

        });
    }

    public static class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar calendar = Calendar.getInstance();
            int yy = calendar.get(Calendar.YEAR);
            int mm = calendar.get(Calendar.MONTH);
            int dd = calendar.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog, this, yy, mm, dd);
        }

        public void onDateSet(DatePicker view, int yy, int mm, int dd) {
            populateSetDate(yy, mm+1, dd);
        }
        public void populateSetDate(int year, int month, int day) {
            Output.setText(month+"/"+day+"/"+year);
        }

    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Selected Date (MM-DD-YYYY): "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/Output"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/changeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select Date"/>

</LinearLayout>

If everything works you should see a screen like this:

emulator_output


NOTE: instead of android.R.style.Theme_Holo_Light_Dialog you can use AlertDialog.THEME_HOLO_LIGHT to get a layout like the one in your screenshot but this last one has been deprecated starting from API 23

References

1 - DatePicker tutorial
2 - some functions called in the tutorial for the Dialogs were deprecated, so this answer provided a fix based on DialogFragments
3 - DatePickerDialog constructor
4 - Holo Light Dialog Theme

Dharman
  • 30,962
  • 25
  • 85
  • 135
Antonino
  • 3,178
  • 3
  • 24
  • 39
  • @UnnatiPatadia ok questions: how are you resolving the Calendar class? you are suggested `import android.icu.util.Calendar;` and `import java.util.Calendar;`. Can you please try with this last one if it's not already your current choice? also: which Android phone and Android version are you using for testing? I'm asking because the screenshot I showed in my answer comes from a real test on the emulator [Nexus 5X, API 26] – Antonino Nov 16 '19 at 01:15
  • My device is MI Note 4. Android version 6.0.1 Marshmallow – Unnati Patadia Nov 18 '19 at 09:39
  • @UnnatiPatadia I tried on a Galaxy Nexus, API 23 [Android 6.0] and the output was as the one you were asking for. Unfortunately I don't have the same phone you are using but for what I just said it might be a problem related to the brand. Have you tried running this same app on different phones too? – Antonino Nov 20 '19 at 01:49
0

Use the SpinnerDatePicker library here https://github.com/drawers/SpinnerDatePicker and the usage is very simple as described in its intro.

 new SpinnerDatePickerDialogBuilder()
            .context(MainActivity.this)
            .callback(MainActivity.this)
            .spinnerTheme(R.style.NumberPickerStyle)
            .showTitle(true)
            .showDaySpinner(true)
            .defaultDate(2017, 0, 1)
            .maxDate(2020, 0, 1)
            .minDate(2000, 0, 1)
            .build()
            .show();  

Hope it helps!

Vanshaj Daga
  • 2,145
  • 11
  • 18
0

Just set

android:datePickerMode="spinner"

in your view xml file

if you want the clear button to be added, you can build a custom view and set actions for bottom buttons

Erfan Gholami
  • 21
  • 1
  • 8
0

In android, we have Date Picker Dialog to pick the date but if you want to change the style of the date picker dialog then you can change the theme of the date picker. these are some Themes you can change according to your needs.

1.AlertDialog.THEME_DEVICE_DEFAULT_DARK

2.AlertDialog.THEME_DEVICE_DEFAULT_LIGHT

3.AlertDialog.THEME_HOLO_DARK

4.AlertDialog.THEME_HOLO_LIGHT

5.AlertDialog.THEME_TRADITIONAL

I'm sharing with you the link where you can find more about Date Picker Dialog with source code.

https://www.android-examples.com/change-datepickerdialog-theme-in-android-using-dialogfragment/

Rahul Goswami
  • 762
  • 6
  • 18