17

I am new on Android Fragments and I want to know that how can I show or implement DatePicker in simple Fragmentand not a FragmentActivity.

For example my class name is:

public class FragmentAddCard extends Fragment {
}

Thanks.

user3555472
  • 836
  • 3
  • 11
  • 38

4 Answers4

45

In your button click call the DateFragment like this

   dob.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            DialogFragment newFragment = new SelectDateFragment();
            newFragment.show(getFragmentManager(), "DatePicker");

        }
    });

Here is the code snippet for DateFragment

  public 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(), 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) {
            dob.setText(month+"/"+day+"/"+year);
            }

    }
Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
  • in the Date Fragment class. I couldnt resolve dob. Please help – Sagar Devanga Jul 28 '15 at 13:04
  • @Sagar Devanga It is TextView to show the selected Date – Don Chakkappan Jul 28 '15 at 13:35
  • 7
    i know but i have both things in different classes and how can i pass the reference of dob or attach a listener. Because it is not allowing me create a constructor with the listener and asking me to use the default constructor. – Sagar Devanga Jul 28 '15 at 15:35
  • see i have two fragment in an activity both having this datefragment..but sometimes it works on one fragment and sometimes second... – Aman Verma Oct 17 '15 at 17:05
  • 1
    `TextView dob= (TextView)getActivity(). findViewById(R.id.dob);` should fix the error when running it inside a activity – saur Feb 26 '16 at 07:23
  • @DonChakkappan thanks dear. Its working fine can you please help me here http://stackoverflow.com/questions/42779110/android-spinner-doesnt-showing-last-selected-item/ – Pranav MS Mar 15 '17 at 05:36
  • `SelectDateFragment must be a public static class to be properly recreated from instance state` exception occurred. – Chirag Savsani Aug 29 '19 at 07:33
  • Nice answer based on this [Android documentation](https://developer.android.com/guide/topics/ui/controls/pickers.html#DatePicker). Let's keep in mind that we can choose the style of the `DatePickerDialog` calling e.g. `return new DatePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog, this, yy, mm, dd);` – Antonino Nov 09 '19 at 14:40
  • fragmentManager is deprecated – Abraham Mathew Dec 13 '19 at 06:19
11

This is other example:

Calendar cal = Calendar.getInstance(TimeZone.getDefault()); // Get current date

// Create the DatePickerDialog instance
DatePickerDialog datePicker = new DatePickerDialog(this,
                    R.style.AppBlackTheme, datePickerListener,
                    cal.get(Calendar.YEAR), 
                                        cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH));
            datePicker.setCancelable(false);
            datePicker.setTitle("Select the date");
datePicker.show();

// Listener
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        String year1 = String.valueOf(selectedYear);
        String month1 = String.valueOf(selectedMonth + 1);
        String day1 = String.valueOf(selectedDay);
        TextView tvDt = (TextView) findViewById(R.id.tvDate);
        tvDt.setText(day1 + "/" + month1 + "/" + year1);

    }
};
joselufo
  • 3,393
  • 3
  • 23
  • 37
2

First of all i can say that,Selected answer is working fine.it is a good approach. But if you want to use MaterailDatePicker with Fragment. I found a solution. Try following for Set DatePicker in Fragment.

Gradle

dependencies {
  compile 'com.wdullaer:materialdatetimepicker:3.1.3'
}

DatePickerFragment

package com.wdullaer.datetimepickerexample;

import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import java.util.Calendar;

/**
 * A simple {@link Fragment} subclass.
 */
public class DatePickerFragment extends Fragment implements DatePickerDialog.OnDateSetListener {

    private TextView dateTextView;
    private CheckBox modeDarkDate;
    private CheckBox modeCustomAccentDate;
    private CheckBox vibrateDate;
    private CheckBox dismissDate;
    private CheckBox titleDate;
    private CheckBox showYearFirst;
    private CheckBox showVersion2;
    private CheckBox limitSelectableDays;
    private CheckBox highlightDays;

    public DatePickerFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.datepicker_layout, container, false);

        // Find our View instances
        dateTextView = (TextView) view.findViewById(R.id.date_textview);
        Button dateButton = (Button) view.findViewById(R.id.date_button);
        modeDarkDate = (CheckBox) view.findViewById(R.id.mode_dark_date);
        modeCustomAccentDate = (CheckBox) view.findViewById(R.id.mode_custom_accent_date);
        vibrateDate = (CheckBox) view.findViewById(R.id.vibrate_date);
        dismissDate = (CheckBox) view.findViewById(R.id.dismiss_date);
        titleDate = (CheckBox) view.findViewById(R.id.title_date);
        showYearFirst = (CheckBox) view.findViewById(R.id.show_year_first);
        showVersion2 = (CheckBox) view.findViewById(R.id.show_version_2);
        limitSelectableDays = (CheckBox) view.findViewById(R.id.limit_dates);
        highlightDays = (CheckBox) view.findViewById(R.id.highlight_dates);

        // Show a datepicker when the dateButton is clicked
        dateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar now = Calendar.getInstance();
                DatePickerDialog dpd = DatePickerDialog.newInstance(
                        DatePickerFragment.this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );
                dpd.setThemeDark(modeDarkDate.isChecked());
                dpd.vibrate(vibrateDate.isChecked());
                dpd.dismissOnPause(dismissDate.isChecked());
                dpd.showYearPickerFirst(showYearFirst.isChecked());
                dpd.setVersion(showVersion2.isChecked() ? DatePickerDialog.Version.VERSION_2 : DatePickerDialog.Version.VERSION_1);
                if (modeCustomAccentDate.isChecked()) {
                    dpd.setAccentColor(Color.parseColor("#9C27B0"));
                }
                if (titleDate.isChecked()) {
                    dpd.setTitle("DatePicker Title");
                }
                if (highlightDays.isChecked()) {
                    Calendar date1 = Calendar.getInstance();
                    Calendar date2 = Calendar.getInstance();
                    date2.add(Calendar.WEEK_OF_MONTH, -1);
                    Calendar date3 = Calendar.getInstance();
                    date3.add(Calendar.WEEK_OF_MONTH, 1);
                    Calendar[] days = {date1, date2, date3};
                    dpd.setHighlightedDays(days);
                }
                if (limitSelectableDays.isChecked()) {
                    Calendar[] days = new Calendar[13];
                    for (int i = -6; i < 7; i++) {
                        Calendar day = Calendar.getInstance();
                        day.add(Calendar.DAY_OF_MONTH, i * 2);
                        days[i + 6] = day;
                    }
                    dpd.setSelectableDays(days);
                }
                dpd.show(getFragmentManager(), "Datepickerdialog");
            }
        });

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        DatePickerDialog dpd = (DatePickerDialog) getFragmentManager().findFragmentByTag("Datepickerdialog");
        if(dpd != null) dpd.setOnDateSetListener(this);
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        String date = "You picked the following date: "+dayOfMonth+"/"+(++monthOfYear)+"/"+year;
        dateTextView.setText(date);
    }
}
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
0
  button_name.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
                     @Override
                     public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
                         String years=""+year;
                         String months=""+(monthOfYear+1);
                         String days=""+dayOfMonth;
                         if(monthOfYear>=0 && monthOfYear<9){
                             months="0"+(monthOfYear+1);
                         }
                         if(dayOfMonth>0 && dayOfMonth<10){
                             days="0"+dayOfMonth;

                         }
                         race_date.setText(months+"/"+days+"/"+years);
                     }
                 }, now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH));
                datePickerDialog.setMinDate(now);
                datePickerDialog.show(getActivity().getFragmentManager(), "Datepicker");
                break;
        }
        return false;
    }
});
Raveendra
  • 141
  • 2
  • 6
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit](https://meta.stackoverflow.com/posts/360251/edit) your answer to add some explanation, including the assumptions you’ve made. [ref](https://meta.stackoverflow.com/a/360251/8371915) – Alper t. Turker Jan 21 '18 at 15:32